EzDevInfo.com

logback

The reliable, generic, fast and flexible logging framework for Java. Logback Home

Where is logback encoder pattern documentation

I've gone through all the documentation of logback and I can't find anywhere the documentation to configure the encoder's pattern when logging, such as:

<encoder>
  <pattern>%d{HH:mm:ss.SSS} %-4relative %-5level %logger{35} - %msg%n</pattern>
</encoder>

I would like a table (like the one that log4j has) explaining the different options to configure the pattern.

Where is the documentation of the pattern? Maybe they are defined in another project?


Source: (StackOverflow)

How to setup commons-logging to use logback?

We use slf4j + logback, and happened to have some 3rd party libraries which use commons-logging. How to I set it up to use logback?


Source: (StackOverflow)

Advertisements

Logback native VS Logback via SLF4J

I have gone through the following article regarding the logging frameworks available for Java: http://michaelandrews.typepad.com/the_technical_times/2011/04/java-logging-reconsidered.html

The author has mentioned using SLF4J with Logback. How is that different from using Logback directly. Wouldn't it be better if one uses Logback directly rather than going for SLF4J, since Logback is built on top of SLF4J.


Source: (StackOverflow)

Why not use java.util.logging?

For the first time in my life I find myself in a position where I'm writing a Java API that will be open sourced. Hopefully to be included in many other projects.

For logging I (and indeed the people I work with) have always used JUL (java.util.logging) and never had any issues with it. However now I need to understand in more detail what I should do for my API development. I've done some research on this and with the information I've got I just get more confused. Hence this post.

Since I come from JUL I'm biased on that. My knowledge of the rest is not that big.

From the research I've done I've come up with these reasons why people do not like JUL:

  1. "I started developing in Java long before Sun released JUL and it was just easier for me to continue with logging-framework-X rather than to learn something new". Hmm. I'm not kidding, this is actually what people say. With this argument we could all be doing COBOL. (however I can certainly relate to this being a lazy dude myself)

  2. "I don't like the names of the logging levels in JUL". Ok, seriously, this is just not enough of a reason to introduce a new dependency.

  3. "I don't like the standard format of the output from JUL". Hmm. This is just configuration. You do not even have to do anything code-wise. (true, back in old days you may have had to create your own Formatter class to get it right).

  4. "I use other libraries that also use logging-framework-X so I thought it easier just to use that one". This is a cyclic argument, isn't ? Why does 'everybody' use logging-framework-X and not JUL?

  5. "Everybody else is using logging-framework-X". This to me is just a special case of the above. Majority is not always right.

So the real big question is why not JUL?. What is it I have missed ? The raison d'ĂȘtre for logging facades (SLF4J, JCL) is that multiple logging implementations have existed historically and the reason for that really goes back to the era before JUL as I see it. If JUL was perfect then logging facades wouldn't exist, or what? Rather than embracing them shouldn't we question why they were necessary in the first place? (and see if those reasons still exist)

Ok, my research so far has led to a couple of things that I can see may be real issues with JUL:

  1. Performance. Some say that performance in SLF4J is superior to the rest. This seems to me to be a case of premature optimization. If you need to log hundreds of megabytes per second then I'm not sure you are on the right path anyway. JUL has also evolved and the tests you did on Java 1.4 may no longer be true. You can read about it here and this fix has made it into Java 7. Many also talk about the overhead of string concatenation in logging methods. However template based logging avoids this cost and it exist also in JUL. Personally I never really write template based logging. Too lazy for that. For example if I do this with JUL:

    log.finest("Lookup request from username=" + username 
       + ", valueX=" + valueX
       + ", valueY=" + valueY));
    

    my IDE will warn me and ask permission that it should change it to:

    log.log(Level.FINEST, "Lookup request from username={0}, valueX={1}, valueY={2}", 
       new Object[]{username, valueX, valueY});
    

    .. which I will of course accept. Permission granted ! Thank you for your help.

    So I don't actually write such statements myself, that is done by the IDE.

    In conclusion on the issue of performance I haven't found anything that would suggest that JUL's performance is not ok compared to the competition.

  2. Configuration from classpath. Out-of-the-box JUL cannot load a configuration file from the classpath. It is a few lines of code to make it do so. I can see why this may be annoying but the solution is short and simple.

  3. Availability of output handlers. JUL comes with 5 output handlers out-of-the-box: console, file stream, socket and memory. These can be extended or new ones can be written. This may for example be writing to UNIX/Linux Syslog and Windows Event Log. I have personally never had this requirement nor have I seen it used but I can certainly relate to why it may be a useful feature. Logback comes with an appender for Syslog for example. Still I would argue that

    1. 99.5% of the needs for output destinations are covered by what is in JUL out-of-the-box.
    2. Special needs could be catered for by custom handlers on top of JUL rather than on top of something else. There's nothing to me that suggests that it takes more time to write a Syslog output handler for JUL than it does for another logging framework.

I'm really concerned that there's something I've overlooked. The use of logging facades and logging implementations other than JUL is so widespread that I have to come to the conclusion that it's me who just doesn't understand. That wouldn't be the first time, I'm afraid. :-)

So what should I do with my API? I want it to become successful. I can of course just "go with the flow" and implement SLF4J (which seems the most popular these days) but for my own sake I still need to understand exactly what is wrong with the JUL of today that warrants all the fuzz? Will I sabotage myself by choosing JUL for my library ?

Testing performance

(section added by nolan600 on 07-JUL-2012)

There's a reference below from Ceki about SLF4J's parametrization being 10 times or more faster than JUL's. So I've started doing some simple tests. At first glance the claim is certainly correct. Here are the preliminary results (but read on!):

  • Execution time SLF4J, backend Logback: 1515
  • Execution time SLF4J, backend JUL: 12938
  • Execution time JUL: 16911

The numbers above are msecs so less is better. So 10 times performance difference is by first actually pretty close. My initial reaction: That is a lot !

Here is the core of the test. As can be seen an integer and a string is construted in a loop which is then used in the log statement:

    for (int i = 0; i < noOfExecutions; i++) {
        for (char x=32; x<88; x++) {
            String someString = Character.toString(x);
            // here we log 
        }
    }

(I wanted the log statement to have both a primitive data type (in this case an int) and a more complex data type (in this case a String). Not sure it matters but there you have it.)

The log statement for SLF4J:

logger.info("Logging {} and {} ", i, someString);

The log statement for JUL:

logger.log(Level.INFO, "Logging {0} and {1}", new Object[]{i, someString});

The JVM was 'warmed up' with the same test executed once before the actual measurement was done. Java 1.7.03 was used on Windows 7. Latest versions of SLF4J (v1.6.6) and Logback (v1.0.6) was used. Stdout and stderr was redirected to null device.

However, careful now, it turns out JUL is spending most of its time in getSourceClassName() because JUL by default prints the source class name in the output, while Logback doesn't. So we are comparing apples and oranges. I have to do the test again and configure the logging implementations in a similar manner so that they actually output the same stuff. I do however suspect that SLF4J+Logback will still come out on top but far from the initial numbers as given above. Stay tuned.

Btw: The test was first time I've actually worked with SLF4J or Logback. A pleasant experience. JUL is certainly a lot less welcoming when you are starting out.

Testing performance (part 2)

(section added by nolan600 on 08-JUL-2012)

As it turns out it doesn't really matter for performance how you configure your pattern in JUL, i.e. whether or not it includes the source name or not. I tried with a very simple pattern:

java.util.logging.SimpleFormatter.format="%4$s: %5$s [%1$tc]%n"

and that did not change the above timings at all. My profiler revealed that the logger still spent a lot of time in calls to getSourceClassName() even if this was not part of my pattern. The pattern doesn't matter.

I'm therefore concluding on the issue of performance that at least for the tested template based log statement there seems to be roughly a factor of 10 in real performance difference between JUL (slow) and SLF4J+Logback (quick). Just like Ceki said.

I can also see another thing namely that SLF4J's getLogger() call is a lot more expensive than JUL's ditto. (95 ms vs 0.3 ms if my profiler is accurate). This makes sense. SLF4J has to do some time on the binding of the underlying logging implementation. This doesn't scare me. These calls should be somewhat rare in the lifetime of an application. The fastness should be in the actual log calls.

Final conclusion

(section added by nolan600 on 08-JUL-2012)

Thank you for all your answers. Contrary to what I initially thought I've ended up deciding to use SLF4J for my API. This is based on a number of things and your input:

  1. It gives flexibility to choose log implementation at deployment time.

  2. Issues with lack of flexibility of JUL's configuration when run inside an application server.

  3. SLF4J is certainly a lot faster as detailed above in particular if you couple it with Logback. Even if this was just a rough test I have reason to believe that a lot more effort has gone into optimization on SLF4J+Logback than on JUL.

  4. Documentation. The documentation for SLF4J is simply a lot more comprehensive and precise.

  5. Pattern flexibility. As I did the tests I set out to have JUL mimic the default pattern from Logback. This pattern includes the name of the thread. It turns out JUL cannot do this out of the box. Ok, I haven't missed it until now, but I don't think it is a thing that should be missing from a log framework. Period!

  6. Most (or many) Java projects today use Maven so adding a dependency is not that big a thing especially if that dependency is rather stable, i.e. doesn't constantly change its API. This seems to be true for SLF4J. Also the SLF4J jar and friends are small in size.

So the strange thing that happened was that I actually got quite upset with JUL after having worked a bit with SLF4J. I still regret that it has to be this way with JUL. JUL is far from perfect but kind of does the job. Just not quite well enough. The same can be said about Properties as an example but we do not think about abstracting that so people can plug in their own configuration library and what have you. I think the reason is that Properties comes in just above the bar while the opposite is true for JUL of today ... and in the past it came in at zero because it didn't exist.


Source: (StackOverflow)

Logging framework incompatibility

I'm building a small Java app and hoping to use logback for logging.

My app has a dependency on an older project that does its logging via

org.apache.commons | com.springsource.org.apache.commons.logging | 1.1.1

...so my plan was to use

org.slf4j | jcl-over-slf4j | 1.5.6

...to redirect the JCL logging to

org.slf4j | slf4j-api | 1.6.0

...and ultimately to

ch.qos.logback | logback-classic | 0.9.22
ch.qos.logback | logback-core | 0.9.22

so my app can log through logback via its slf4j API while the old library code can log into the same location via the redirection.

Alas, this results in

java.lang.NoSuchMethodError: org.slf4j.spi.LocationAwareLogger.log(Lorg/slf4j/Marker;Ljava/lang/String;ILjava/lang/String;Ljava/lang/Throwable;)V
at   org.apache.commons.logging.impl.SLF4JLocationAwareLog.info(SLF4JLocationAwareLog.java:141)

I've tried higher and lower verision numbers on some of these jars and also digging through API documentation and such... but I'm unable to find and solve the problem.

Help, please?

Although logback is considered the "strategic" logging framework, I have some leeway in which logging mechanism I ultimately use. I'd hope to use either logback or log4j, though, and I definitely want to merge the old project's logging into whatever the "new" logging framework ends up being, via a common configuration.


Source: (StackOverflow)

Best practices for using Markers in SLF4J/Logback

We are using SLF4J+Logback combination at our project for a while now and are quite happy with it, but our logging strategy is fairly simple, using straightforward class based loggers and no fancy stuff like MDC or Markers.

What I want to know is if anybody in the community actually uses these features and how they are used to improve logging/filtering.

I am specially interested in where, why and how would one use[1] Markers for logging. They strike me as a pretty neat feature for adding semantic context into the logging - e.g. while a class may be handling multiple concerns, one may use task/concern specific markers to discriminate log statements.

What may be the best practices, conventions or strategies for creating and using markers in logging.

Update: I guess, what I am really after is not so much why to use markers, but rather the how part — is there some good practices of naming markers (e.g. using plain text with spaces or dash/underscore/punctuation delimited keyword style names), should there be some sort of pool of "standard names", naming stuff based on the business functions. The questions I can probably figure out for myself, but if I want to use these features systematically and introduce them to a team of developers, it makes sense to have some formalizeable set of guidelines around...


[1] - By asking how to use markers I am not really asking how to use API (it is really quite straight forward) - I am rather referring to the more general level of how would one set up logging around using markers consistently


Source: (StackOverflow)

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

  • Regarding Eclipse IDE (Indigo, Juno and Kepler (32 and 64 bit versions))
  • Platforms: Windows, Ubuntu, Mac
  • m2e version: 1.1.0.20120530-0009, 1.2.0.20120903-1050, 1.3.0.20130129-0926,
    1.4.0.20130601-0317

General info

The above error came after updating the m2e to version 1.1. By removing m2e 1.1 and rolling back to m2e 1.0 everything worked fine. I tried to repeat the problem in Windows and Ubuntu and it gave me the exact same error. Numerous configurations of the slf4j-api and logback were tested but none seem to work.

The error appears in any maven project even without declaring slf4j dependency.

  • New Maven Project--> maven-archetype-quickstart

    and

  • New Maven Project--> Simple project without archetype selection

    result to

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".

Testing enviroments and configurations

Tested with Eclipse Indigo and Eclipse Juno (32 and 64 bit both) on Mac, 32 bit on Ubuntu and 64 and 32 bit on Windows. Tested fresh installs of Juno Classic, Juno Modelling tools, Kepler Standard, Kepler Modelling Tools and produced the same error.

The error appears with clean, install, test, deploy, generate-sources, validate , compile , package, integration-test, verify and combinations of the goal clean with the rest goals. It appears also with parameters -e and -X. There was an attempt to delete the m2e repository and download it from scratch but again without success. It should me mentioned that it was tested in 3 different machines and virtual box all the above systems but it produced the same error.

Tried all different logback configurations (from 1.0.4 to 1.0.13) that resolve the slf4j-api and logback-core dependencies, but all produce the same error:

<dependency>
   <groupId>ch.qos.logback</groupId>
   <artifactId>logback-classic</artifactId>
   <version></version>
</dependency>

Tried all different (from 1.6.1 to 1.7.5 ) slf4j-simple configurations.

<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-simple</artifactId>
   <version></version>
   <scope>compile</scope>
</dependency>

Tried all different (from 1.6.1 to 1.7.5 ) log4j-over-slf4j configurations.

<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>log4j-over-slf4j</artifactId>
   <version></version>
   <scope>compile</scope>
</dependency>

Tried all different (from 1.6.1 to 1.7.5 ) slf4j-jdk14 configurations.

<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-jdk14</artifactId>
   <version></version>
   <scope>compile</scope>
</dependency>

Tried all different (from 1.6.1 to 1.7.5 ) slf4j-log4j12 configurations.

<dependency>
     <groupId>org.slf4j</groupId>
     <artifactId>slf4j-log4j12</artifactId>
     <version></version>
     <scope>compile</scope>
</dependency>

Tried slf4j-nop 1.7.5 configuration.

<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-nop</artifactId>
  <version>1.7.5</version>
  <scope>compile</scope>
</dependency>

Last but not least the logs are saved and printed despite the error.


Ways to reproduce the error

  • Download Eclipse Juno, Indigo or Kepler 32 or 64 bit (All installations will cause the same error).

  • Right Click on the project->Runs As->clean install (or any other goal mentioned above)

The first line on the console will be

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

P.S. Existing projects will produce the same error after updating the m2e version to 1.1.0.20120530-0009, 1.2.0.20120903-1050, 1.3.0.20130129-0926, 1.4.0.20130601-0317


Updates

EDIT

m2e support site:

  • The above question was posted as a bug in m2e support site and the answer from Igor Fedorenko was that

    There are no immediate plans to suppress this message.

    For viewing the above bug please refer to m2e official support site


EDIT 2

  • The above error indication is present also to m2e version 1.2.0.20120903-1050


EDIT 3

  • The above error indication is present also to m2e version 1.3.0.20130129-0926


EDIT 4

  • The above error indication is present also to m2e version 1.4.0.20130601-0317


EDIT 5

                              ***Reported FIXED***
  • The above error is reported as fixed for m2e version 1.5.0/Luna M3(Target Milestone). The version is not yet available for download.
  • Luna M3 is scheduled for Nov. 15th.
  • Latest dev build are available here
  • More information about the m2e milestones you can find at the m2e main repository.

Source: (StackOverflow)

How can I configure Logback to log different levels for a logger to different destinations?

How can I configure Logback to log different levels for a logger to different destinations?

For example, given the following Logback configuration, will Logback record INFO messages to STDOUT and ERROR messages to STDERR?

(Note that this example is a variation of example logback-examples/src/main/java/chapters/configuration/sample4.xml shown in Chapter 3: Logback Configuration).

<configuration>
  <appender name="STDOUT"
   class="ch.qos.logback.core.ConsoleAppender">
   <encoder>
     <pattern>
        %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
      </pattern>
    </encoder>
  </appender>
  <appender name="STDERR"
   class="ch.qos.logback.core.ConsoleAppender">
   <encoder>
     <pattern>
        %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
      </pattern>
    </encoder>
    <target>System.err</target>
  </appender>
  <!-- What is the effective level of "chapters.configuration"? -->
  <logger name="chapters.configuration" level="INFO" additivity="false">
    <appender-ref ref="STDOUT" />
  </logger>
  <logger name="chapters.configuration" level="ERROR" additivity="false">
    <appender-ref ref="STDERR" />
  </logger>

  <!-- turn OFF all logging (children can override) -->
  <root level="OFF">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>

Source: (StackOverflow)

How to change root logging level programmatically

I have the following logback.xml file:

<configuration debug="true"> 

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> 
<encoder>
  <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>

<root level="debug">
  <appender-ref ref="STDOUT" />
</root>
</configuration>

Now, upon the occurrence of a specific event, I want to programmatically change the level of the root logger from debug to error. I can't use variable substitution, it is mandatory that I do this within the code.

How can it be done ? Thanks.


Source: (StackOverflow)

How to prevent logback from outputting its own status at the start of every log?

This seems like a carelessness error, but I can't seem to find the cause. Logging with logback/slf4j (most recent version slf4j-api-1.6.1, logback core/classic 0.9.24). Simplest log configuration for testing is:

<configuration>
 <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
  <layout class="ch.qos.logback.classic.PatternLayout">
   <!-- DONT USE THIS FORMATTER FOR LIVE LOGGING THE %L LINE NUMBER OUTPUTTER IS SLOW -->
   <pattern>%le %-1r [%c{1}:%L] %m%n</pattern>
  </layout>
 </appender>
 <root level="DEBUG">
  <appender-ref ref="stdout" />
 </root>
</configuration>

Every log setup starts with logback's internal status lines:

11:21:27,825 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
11:21:27,826 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback-test.xml] at [file:.../logback-test.xml]
11:21:28,116 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
11:21:28,124 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
11:21:28,129 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [stdout]
11:21:28,180 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Pushing component [layout] on top of the object stack.
11:21:28,206 |-WARN in ch.qos.logback.core.ConsoleAppender[stdout] - This appender no longer admits a layout as a sub-component, set an encoder instead.
11:21:28,206 |-WARN in ch.qos.logback.core.ConsoleAppender[stdout] - To ensure compatibility, wrapping your layout in LayoutWrappingEncoder.
11:21:28,206 |-WARN in ch.qos.logback.core.ConsoleAppender[stdout] - See also http://logback.qos.ch/codes.html#layoutInsteadOfEncoder for details
11:21:28,207 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to DEBUG
11:21:28,207 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [stdout] to Logger[ROOT]

which is, according to the docs, the format logback uses for default. It then finishes reading the config (which is set up to output a different format) and continues with the properly formatted output. There's a config parameter <configuration debug="false"> which does not affect this.

Anyone know how to shut this off?


Source: (StackOverflow)

How to use MDC with thread pools?

In our software we extensively use MDC to track things like session IDs and user names for web requests. This works fine while running in the original thread. However, there's a lot of things that need to be processed in the background. For that we use the java.concurrent.ThreadPoolExecutor and java.util.Timer classes along with some self-rolled async execution services. All these services manage their own thread pool.

This is what Logback's manual has to say about using MDC in such an environment:

A copy of the mapped diagnostic context can not always be inherited by worker threads from the initiating thread. This is the case when java.util.concurrent.Executors is used for thread management. For instance, newCachedThreadPool method creates a ThreadPoolExecutor and like other thread pooling code, it has intricate thread creation logic.

In such cases, it is recommended that MDC.getCopyOfContextMap() is invoked on the original (master) thread before submitting a task to the executor. When the task runs, as its first action, it should invoke MDC.setContextMapValues() to associate the stored copy of the original MDC values with the new Executor managed thread.

This would be fine, but it is a very easy to forget adding those calls, and there is no easy way to recognize the problem until it is too late. The only sign with Log4j is that you get missing MDC info in the logs, and with Logback you get stale MDC info (since the thread in the tread pool inherits its MDC from the first task that was ran on it). Both are serious problems in a production system.

I don't see our situation special in any way, yet I could not find much about this problem on the web. Apparently, this is not something that many people bump up against, so there must be a way to avoid it. What are we doing wrong here?


Source: (StackOverflow)

Suppress all Logback output to console?

How can I configure Logback to suppress all of its output to the console (standard output)? In particular, I wish to suppress (or redirect) Logback's own log messages such as the following:

16:50:25,814 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
16:50:25,814 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [file:/opt/dap/domains/ap0491/uat1/domain/instance-config/logback.xml]
16:50:25,816 |-WARN in ch.qos.logback.classic.LoggerContext[default] - Resource [logback.xml] occurs multiple times on the classpath.
16:50:25,816 |-WARN in ch.qos.logback.classic.LoggerContext[default] - Resource [logback.xml] occurs at [file:/opt/dap/domains/ap0491/uat1/domain/instance-config/logback.xml]
16:50:25,816 |-WARN in ch.qos.logback.classic.LoggerContext[default] - Resource [logback.xml] occurs at [file:/opt/dap/domains/ap0491/uat1/domain/instance-config/logback.xml]
16:50:25,923 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
16:50:25,924 |-INFO in ch.qos.logback.classic.turbo.ReconfigureOnChangeFilter@1a15291 - Will scan for changes in file [/opt/dap/domains/ap0491/uat1/domain/instance-config/logback.xml] every 60 seconds. 

I need to disable all logging to standard output because our production environment disallows applications from printing any messages to standard output.

Note I'm using Logback 0.9.21, SLF4J 1.6.0, and our application runs in WebLogic 10.3.2.


Source: (StackOverflow)

Log4j 2.0 and SLF4J and the never ending future of java logging frameworks [closed]

So I just found out today that Log4J 2.0 is now actively being developed, there is an alpha version and it is said to replace logback.

Right now in my app I have close to 4 maybe more logging frameworks:

  • Java Util Logging
  • log4j
  • slf4j
  • logback (ignored thanks to a maven provided hack)
  • commons logging (ignored thanks to a maven provided hack)
  • And tomcat has its own JULI adapter

I have been using log4j (1.2.x) because frankly I just haven't needed the features of the newer guys but I have been tempted lately to switch to SLF4J and mainly because I don't want to have rewrite my complicated log4j configurations files to a new format (logback).

Now my question is in terms of what I should code against is SLF4J the right choice for the future given log4j 2.0.

It seems like I should just stick with old log4j (1.2.x) as it is the lowest common denominator?

UPDATE: on further examination of log4j 2.0 while very similar it appears the configuration is not backward compatible with log4j 1.2. Looks like logback is the best choice.


Source: (StackOverflow)

Logback and Jboss 7 - don't work together?

I am having a curious problem. I had this Java application which was previously deployed in tomcat and happily used logback classic as an slf4j implementation. Now when we tried to deploy the same app in a jboss 7.1.final server it doesn't even deploy the application maoning about java.lang.ClassCastException: org.slf4j.impl.Slf4jLoggerFactory cannot be cast to ch.qos.logback.classic.LoggerContext This is the offending line of code

final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

The class that has his is spring injected and that is failing - hence the whole application cannot be deployed. Anyone got a solution to this? Thanks in advance

After looking in this site plus other forums I realised that Jboss 7 comes bundled with it's own slf4j implementation and implement the same ILoggerFactory interface that LoggerContext in logback does. Our application tried to get an instance of the same but the app server imposes it's own slf4j implementation.

I tried to modify the module.xml in jboss\modules\org\slf4j\impl\main and pointed it to logback jars.

<resources>
    <resource-root path="logback-classic-0.9.28.jar"/>
    <resource-root path="logback-core-0.9.28.jar"/>
</resources>

Now when I start the application I am getting a serious error

Exception starting filter WicketFilter: java.lang.ClassCastException: ch.qos.logback.classic.LoggerContext cannot be cast to ch.qos.logback.classic.LoggerContext

I am at my wits end. Any jboss and logback experts can help? Thanks in advance


Source: (StackOverflow)

Why calling LoggerFactory.getLogger(...) every time is not recommended?

I've read tons of posts and documents (on this site and elsewhere) pointing that the recommended pattern for SFL4J logging is:

public class MyClass {
    final static Logger logger = LoggerFactory.getLogger(MyClass.class);

    public void myMethod() {
        //do some stuff
        logger.debug("blah blah blah");
    }
}

My boss prefers we just use a wrapper to intercept log calls and avoid boiler plate code for declaring the logger on every class:

public class MyLoggerWrapper {
    public static void debug(Class clazz, String msg){
        LoggerFactory.getLogger(clazz).debug(msg));
    }
}

and simply using it like this:

public class MyClass {

    public void myMethod() {
        //do some stuff
        MyLoggerWrapper.debug(this.getClass(), "blah blah blah");
    }
}

I presume instantiating a logger every time we log is somewhat expensive but I've been unable to find any document backing that assumption. Besides he says surely the framework (LogBack or Log4J we're still deciding) will "cache" the loggers and also that in any case the servers are running very much below their capacity so it is not an issue.

Any help pointing out potential problems with this approach?


Source: (StackOverflow)