check enable of logger level vs don't check in SLF4J\Logback - java

I using SLF4J and Logback for logging infrastructure at my application.
I using Logger.isDebugEnable() method before any log, for sample:
if(logger.isDebugEnable())
logger.debug('process transaction....')
goal of above code is : don't construct string process transaction.... in heap when log level is not Debug.
My question is:
Is there benefit between my code style or direct logger.debug('process transaction....') without check enable log level?

This is a legacy from the log4j project. slf4j has introduced the {} construction which allow you to use:
logger.debug("{}: {}", "MyClass", "Message to show to user");
where the logger backend first checks for "is...Enabled()" and then constructs the logger string.
As the backend checks itself you do not need to, and the if clause can be removed leaving only the logger statement itself.

Related

Send log messages as JSON

I am using spring boot in a project and currently exploring the logging behaviour. For that I'm using the zipkin service.
I have exported my logs to a json file using proper logback.xml:
{"#timestamp":"2018-07-12T17:53:44.613+05:30","#version":"1","message":"in meth3","logger_name":"com.example.demo.Controller.Controller","thread_name":"http-nio-8089-exec-3","level":"INFO","level_value":20000,"traceId":"62bcfafad3a37a09","spanId":"62bcfafad3a37a09","spanExportable":"true","X-Span-Export":"true","X-B3-SpanId":"62bcfafad3a37a09","X-B3-TraceId":"62bcfafad3a37a09","caller_class_name":"com.example.demo.Controller.Controller","caller_method_name":"meth3","caller_file_name":"Controller.java","caller_line_number":43,"appname":"pom.artifactId_IS_UNDEFINED","version":"pom.version_IS_UNDEFINED"}
Is there a way so that I could insert a jsonObject in my message part of the log. Something like:
logger.info(<some_json_object>)
I have tried searching a way extensively but to no avail. Is it even possible?
The slf4j API only takes String as the input to the info, debug, warn, error messages.
What you could do is create your own JsonLogger wrapper, which takes a normal Logger (maybe wraps around it), which you could include at the top of your classes like:
private static final JsonLogger logger = new JsonLogger(LoggerFactory.getLogger(MyClass.class));
You can then use Jackson, GSON or your favourite object to JSON mapper inside your JsonLogger so that you could do what you want. It can then offer the info, debug, warn, error methods like a normal logger.
You can also create your own JsonLoggerFactory which encapsulates this for you so that the line to include in each class is more concise.

How do I change a remote application's logback log level through http (rest)?

How do I change a remote application's logback log level through http (rest)? to
#Controller
public class ChangeLog2Controller {
#PostMapping("/api/testlog1")
public ResponseModel testLogeBack(#RequestBody LogLevelModel levelModel) {
...
}
}
Something like this ...
#PostMapping("/api/testlog1")
public ResponseModel testLogeBack(#RequestBody LogLevelModel levelModel) {
// change the log level for the root logger
Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
rootLogger.setLevel(...);
// change the log level for a specific logger
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
Logger specificLogger = loggerContext.getLogger("com.some.specific.package");
specificLogger.setLevel(...);
}
... where the parameter passed into setLevel() is something like Level.INFO which would, I presume, be derived from your LogLevelModel.
Note: if you are looking for some way to dynamically change logging configuration and a JMX client (rather than a HTTP client) would suffice then Logback already provides a JMX Configurator which yuou can engage by simply adding the following to your logback.xml: <jmxConfigurator />. This exposes a JMX MBean which you can use to view and set log levels.
Edit 1: based on the comments below it seems like your requirement might be to invoke WebApplicationA and somehow enable WebApplicationA to change the log level for loggers inside WebApplicationB? If so, then either
WebApplicationA has to use the JMXConfigurator MBean exposed by WebApplicationB. There are examples of Java JMX clients here and here. However, in order to expose the JMXConfigurator you must have some control over WebApplicationB's logback.xml and, if so, then perhaps you also have some control over WebApplicationB's implementation in which case it might be easier to just expose a simple setLogLevel REST endpoint in WebApplicationB and let WebApplicationA invoke that rather than playing around with a Java JMX client.
Or
WebApplicationB has to expose a changeLogLevel REST API (with an implementation like the one I provided above) which WebApplicationA can invoke.
The only other alternative is that WebApplicationA somehow changes the logback.xml used by WebApplicationB and WebApplicationB's logback.xml starts looks like this ...
<configuration scan="true" scanPeriod="30 seconds" >
...
</configuration>
... so that any changes made to this file on WebApplicationB's classpath are picked up within (for example) 30 seconds. But, since WebApplicationB's logback.xml is likely to be embedded in a WAR (or similar) this approach seems very awkward and very likely undesireable.

Logger not functioning properly

I am using java.util.logging.Logger Class for logging in my application. I have added FileHandler so that the application log is stored directly in log.txt file.
But for some reason, after the application is terminated the log is far from complete. On cmd, I can see all the statements but they are never appended to the file.
I have set FileHandler to the Logger by:
private void setLogger() {
try {
FileHandler hand = new FileHandler("log/log.txt", true);
hand.setFormatter(new SimpleFormatter());
Logger log = Logger.getLogger(ImageRename.MAIN_LOG);
//log.setUseParentHandlers(false);
log.addHandler(hand);
log.setLevel(Level.ALL);
} catch (IOException e) {
System.out.println("Could Not set logger");
}
}
Any problem with flushing? How to solve it? Thanks.
PS: On debugging, I have noticed that in between
Logger.getLogger(ImageRename.MAIN_LOG).getHandlers().length
returns 0. Where as it should return 1. Initially it was printing 1, but somewhere down the line it becomes zero.
The problem is ... garbage collection.
What is happening is likely the following:
You call Logger.getLogger(ImageRename.MAIN_LOG);
You setup the logger.
Java notices it is unreferenced, and discards it.
You call Logger.getLogger(ImageRename.MAIN_LOG); and expect to get the same logger.
A fresh logger is set up with default configuration.
You can avoid this by two measures:
Use a configuration file logging.properties for configuration. When creating the logger, the Java logging API will consult the configuration, and thus recreate it appropriately.
Use static references. This is a best practise anyway. Equip each class with a logger:
private final static Logger LOG =
Logger.getLogger(ExampleClass.class.getName());
While the class is loaded it then should not be garbage collected AFAICT.
See e.g. http://www.massapi.com/class/fi/FileHandler.html for an example (found via Google)
Note the following line, which may be your problem:
fileHandler.setLevel(Level.ALL);
(Note: this is the level of the Handler, not of the Logger or message.)
For debugging, first try to get messages at an ERROR level logged. Messages at level INFO and below are often supressed by default.
Also try setting the logging level as soon as possible. In my experience, the most reliable way of configuring Java logging is by using a properties file, and invoking Java with:
-Djava.util.logging.config.file=path/to/file/logging.properties
The reason is that the settings you do sometimes are not applied to loggers created before you loaded the settings, once some changes have been made to the logging.

Logging in spring MVC

I'm currently working on a web application using Spring MVC, and I use the #ExceptionHandler annotation in every controllers of the application.
So basically I got a method like this:
#ExceptionHandler(RuntimeException.class)
public String handleException(RuntimeException ex) {
injectedService.notifyAndLogException(ex.getMessage());
return ("error_page");
}
My idea is to log and send an email to an application administrator in the injected service.
For now, I've tried to read some documentation about logging in spring application, and all the things I've seen is setting a static logger in each controller.
Like this:
private final Logger log = LoggerFactory.getLogger(Controller.class);
#ExceptionHandler(RuntimeException.class)
public String handleException(RuntimeException ex) {
log.info("Logging error");
injectedService.notifyException(ex.getMessage());
return ("error_page");
}
I'd like to know what is the point to use a logger in each controller instead of using it in one point only (the service)?
I'd like to know what is the point to use a logger in each controller instead of using it in one point only
If you use a single logger for the whole application, then every log message will be logged as coming from the same component. By using a logger per class or component, then your log files will contain information about which component logged the message.
For example, when you do:
Logger log = LoggerFactory.getLogger(Controller.class);
This creates a logger with the name of the Controller class, which will generally be displayed in the log file, e.g.
2012-03-07:12:59:00 com.x.y.Controller Hello!
This is just a convention, but it's a good one that I advise you follow.
a logger in each of your class files enables you get 'debug' or 'info' level when you are in production, or not able to connect a debugger.
Since you can limit via package or even class file name, what is logged, you can pin point to find errors, or to see what is happening under different load situations (concurrency problems, resources used ). If you use one generic logger, then you may flood your log file.
With the logger in the class that received the exception, you may be able to get at class variables that are not being passed into your exception handler.
I would also recommend that you do not do
injectedService.notifyAndLogException(ex.getMessage());
but pass the exception into your notify. While stack traces can be notorious verbose, the messages usually are not very help full ( NullPointerException without a stacktrace ? ). In your notify service you can set the subject to ex.getMessage() and the body have the entire stack trace.
Your controllers can extend an abstract class that declares a logger like that
protected Logger logger = LoggerFactory.getLogger( getClass() );
This logger can be used in all controller and it will prefix the log message with the controller class name.

java logging API, disable logging to standard output

Using the standard java logging API (import java.util.logging.Logger), after the construction:
Logger l = Logger.getLogger("mylogger");
I am already able to log something. Since it has not a FileHandler, it doesn't write anything to disk.
l.severe("test with no handler");
It writes (some, not all) the log messages to output.
How can I disable this feature?
thanks in advance
Agostino
The question arises if you don't know the default configuration of java util logging.
Architectural fact:
0)Every logger whatever its name is has the root logger as parent.
Default facts:
1) the logger property useParentHandlers is true by default
2) the root logger has a ConsoleHandler by default
So. A new logger, by default sends its log records also to his parent(point 1) that is the root logger(point 0) wich, by default, logs them to console(point 2).
Remove console logging is easy as:
Logger l0 = Logger.getLogger("");
l0.removeHandler(l0.getHandlers()[0]);
Standard Loggers in Java are in a hierarchical structure and child Loggers by default inherit the Handlers of their parents. Try this to suppress parent Handlers from being used:
l.setUseParentHandlers(false);
By disable this feature you mean you don't want to log anything at all? If that's the case you have to set the level of that logger to NONE
For instance, if you're using a logging properties file you can set:
mylogger.level=NONE

Categories

Resources