I have a Java maven application in which I have created a swing GUI.
I am using logback-classic for logging purposes. logback.xml is present under the src/main/resources directory.
When I run the application using eclipse "Run As Java Application", it is working as intended and application is logging to the console and log file.
But after exporting the application as a runnable JAR file and double clicking to run the application, it is not logging to file.
When I opened command prompt and execute application using "java -jar myjarfile.jar", I am able to see the console logs, but it is using the default logback configuration.
I tried giving additional parameter, -Dlogback.configurationFile="path-to-file/logback.xml" and I am getting the below error,
Failed to instantiate [ch.qos.logback.classic.LoggerContext] Reported
exception: java.lang.IllegalArgumentException: name
at sun.misc.URLClassPath$Loader.findResource(Unknown Source)
at sun.misc.URLClassPath$1.next(Unknown Source)
at sun.misc.URLClassPath$1.hasMoreElements(Unknown Source)
at java.net.URLClassLoader$3$1.run(Unknown Source)
at java.net.URLClassLoader$3$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader$3.next(Unknown Source)
at java.net.URLClassLoader$3.hasMoreElements(Unknown Source)
at sun.misc.CompoundEnumeration.next(Unknown Source)
at sun.misc.CompoundEnumeration.hasMoreElements(Unknown Source)
at ch.qos.logback.core.util.Loader.getResources(Loader.java:73)
at ch.qos.logback.classic.util.ContextInitializer.multiplicityWarning(ContextInitializer.java:183)
at ch.qos.logback.classic.util.ContextInitializer.statusOnResourceSearch(ContextInitializer.java:175)
at ch.qos.logback.classic.util.ContextInitializer.findConfigFileURLFromSystemProperties(ContextInitializer.java:111)
at ch.qos.logback.classic.util.ContextInitializer.findURLOfDefaultConfigurationFile(ContextInitializer.java:120)
at ch.qos.logback.classic.util.ContextInitializer.autoConfig(ContextInitializer.java:148)
at org.slf4j.impl.StaticLoggerBinder.init(StaticLoggerBinder.java:84)
at org.slf4j.impl.StaticLoggerBinder.(StaticLoggerBinder.java:55)
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:412)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:357)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:383)
at com.esignature.tools.templatemigration.ConverterGUI.(ConverterGUI.java:35)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:59)
I don't know what I am missing and I want to log from runnable JAR to the log file.
It is confusing because it is working from eclipse but not from the exported runnable JAR.
Below is the logback.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="LOG_HOME" value="C:/template converter logs" />
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level - %msg%n</pattern>
</encoder>
</appender>
<appender name="rollingFile"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/applog-%d{yyyy-MM-dd}.log</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT" />
<appender-ref ref="rollingFile" />
</root>
</configuration>
The error you are facing is because there is two logback.xml configuration, one is in your classpath and you are trying to override/add another one using -Dlogback.configurationFile
In my case when packaging the runnable JAR I changed the pom configuration to this.
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
Note the executable set to true, this makes sure that a MANIFEST.MF file is added to the JAR package.
So in order to make this work with this config I added this property to my application.yml/application.properties
logging:
config: file:D:\\LogConfig\\logback.xml
Then I proceed to generate the JAR file using clean, install mvn commands.
From there running the JAR file using java -jar myJar.jar works fine and there is no need to add arguments to search the application.yml or logback.xml. That is because the properties is being loaded from within the jar and the log config from the specified route on the application.yml .
Using maven shade plugin to generate a shaded JAR file that includes the dependencies and the custom logback.xml is one working solution that I utilized.
Now when I run this JAR file (either from command line or by double-clicking it), logs are generated in the specified location as expected.
I'm migrating a legacy app to Spring Boot and I've faced with the following problem: when I start the app it fails because of the following exception:
Exception in thread "main" java.lang.IllegalStateException: Logback
configuration error detected: ERROR in
ch.qos.logback.core.joran.spi.Interpreter#10:21 - no applicable action
for [BufferedIO], current ElementPath is
[[configuration][appender][BufferedIO]]
ERROR in ch.qos.logback.core.joran.spi.Interpreter#11:25 - no
applicable action for [ImmediateFlush], current ElementPath is
[[configuration][appender][ImmediateFlush]]
at
org.springframework.boot.logging.logback.LogbackLoggingSystem.loadConfiguration(LogbackLoggingSystem.java:161)
at
org.springframework.boot.logging.logback.LogbackLoggingSystem.reinitialize(LogbackLoggingSystem.java:207)
at
org.springframework.boot.logging.AbstractLoggingSystem.initializeWithConventions(AbstractLoggingSystem.java:65)
at
org.springframework.boot.logging.AbstractLoggingSystem.initialize(AbstractLoggingSystem.java:50)
at
org.springframework.boot.logging.logback.LogbackLoggingSystem.initialize(LogbackLoggingSystem.java:114)
at
org.springframework.boot.logging.LoggingApplicationListener.initializeSystem(LoggingApplicationListener.java:299)
at
org.springframework.boot.logging.LoggingApplicationListener.initialize(LoggingApplicationListener.java:272)
at
org.springframework.boot.logging.LoggingApplicationListener.onApplicationEnvironmentPreparedEvent(LoggingApplicationListener.java:235)
at
org.springframework.boot.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:208)
at
org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
at
org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at
org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:122)
at
org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:72)
at
org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54)
at
org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:338)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:309)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1187)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1176)
at com.some_company.SomeApp.main(SomeApp.java:28)
So Logback can't resolve BuferredIO and ImmediateFlush properties. I've tried to see their docs but it seems to be out-of-date as it says such properties exist + I've found e.g. for OutputStreamAppender that it doesn't have the immediateFlush property while according to the docs it should.
I can't find any info on if Logback still supports the following properties now. Could you please help and suggest some ideas on how I can achieve the same result as with the properties previously? Maybe they are somewhere else:)
Thank you very much!:)
UPDATE: Adding a Logback configuration snapshot:
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${logdir}/some-app.log</File>
<Append>true</Append>
<BufferedIO>false</BufferedIO>
<ImmediateFlush>true</ImmediateFlush>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<FileNamePattern>${logdir}/archive-some-app.%i.log.zip</FileNamePattern>
<MinIndex>1</MinIndex>
<MaxIndex>10</MaxIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>20MB</MaxFileSize>
</triggeringPolicy>
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<fieldNames>
<timestamp>timestamp</timestamp>
</fieldNames>
</encoder>
</appender>
Logback version is 1.1.7 (was previously before the migration)
Although ImmediateFlush is a valid configuration property for OutputStreamAppender (which RollingFileAppender extends) in the latest version of Logback (and hence is referenced in the latest docs) this was only added to OutputStreamAppender here in Feb 2017. So, immediateFlush is not a valid property of OutputStreamAppender (and hence is inaccessible from RollingFileAppender) in v1.1.7
This explains the following error:
no applicable action for [ImmediateFlush], current ElementPath is [[configuration][appender][ImmediateFlush]]
BufferedIO is an old configuration property which is no longer supported by Logback.
This explains the following error:
no applicable action for [BufferedIO], current ElementPath is [[configuration][appender][BufferedIO]]
In summary, you might consider upgrading to the latest Logback and just remove <BufferedIO>false</BufferedIO>. Or, continue to use v1.1.7 and remove both of these: <BufferedIO>false</BufferedIO> and <ImmediateFlush>true</ImmediateFlush>.
I'm using Tomcat to deploy a java webapp.
I get a very long stacktrace, in short:
GRAVE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/new-webapp]]
[...]
Caused by: java.lang.NoClassDefFoundError: Lorg/apache/logging/log4j/Logger;
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Class.java:2509)
at java.lang.Class.getDeclaredFields(Class.java:1819)
at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:106)
at org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:256)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationFilterAnnotations(WebAnnotationSet.java:105)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:64)
at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:335)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:782)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:306)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:95)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5150)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
... 6 more
Caused by: java.lang.ClassNotFoundException: org.apache.logging.log4j.Logger
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1305)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1139)
... 20 more
[...]
Now, the error is pretty clear. For some reason, the log4j bundle is not in the classpath.
The application is a maven webapp, and the pom.xml is like this:
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wb</groupId>
<artifactId>new-webapp</artifactId>
<packaging>war</packaging>
<version>0.0.1</version>
<properties>
<log4j.version>2.5</log4j.version>
</properties>
<dependencies>
[...]
<!-- Logging -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
[...]
</project>
If I go to the project properties, under Libraries->Maven Dependencies I see this:
Libraries were found, downloaded and they are in the classpath.
I also tried to open a java class inside my project and declare
org.apache.logging.log4j.Logger Logger;
No errors, the Logger interface is found.
What's going on here? Why does Tomcat fail to start even if libraries are in the classpath?
Edit - this is the log4j configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="Console" />
</Root>
</Loggers>
</Configuration>
By the description you've made, I assume you are working with Eclipse.
Well, you'd better go to Project properties -> Deployment assembly and ensure that the maven dependencies entry is included.
I've experimented often that this configuration gets missed whenever you execute Maven -> Update Project.
I'm working with Eclipse and I had same problem every time I made changes in my pom.xml. I don't know why but Eclipse delete the Maven Dependencies.
Solution: rigth click on project, select Properties, choose Deployment Assembly and verify in column "Source" a row called "Maven Dependencies". If it isn't there, click on Add..., Java Build Path Entries and click on Maven Dependencies. Finally Apply and close.
Ensure that the log4j libraries are not included already in the Tomcat runtime (nor the endorsed directories), because it could produce conflict about classloading policy.
I just started using of log4j2.
But i found that log4j2 including library name in stacktrace.
How can i disable that?
Here is an example:
java.lang.NullPointerException
at com.sev.controllers.UserController.login(UserController.java:35) ~[UserController.class:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_31]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_31]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_31]
at java.lang.reflect.Method.invoke(Method.java:483) ~[?:1.8.0_31]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) ~[spring-web-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) ~[spring-web-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) ~[spring-webmvc-4.1.7.RELEASE.jar:4.1.7.RELEASE]
Im talking about that name in [] braces.
Here is my log4j config
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="org.apache.log4j.xml" level="INFO"/>
<Logger name="org.hibernate" level="INFO"/>
<Logger name="org.springframework" level="INFO"/>
<Root level="debug">
<AppenderRef ref="STDOUT"/>
</Root>
</Loggers>
</Configuration>
And here is my versions:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.3</version>
</dependency>
Forget to mention that my app is spring-boot based.
Your configuration's PatternLayout pattern does not contain an explicit exception converter. Log4j will provide a default which is %xEx. This includes the jar file etc.
You can change this by explicitly specifying setting the simple %ex converter. So your pattern ends in ...%m%ex%n.
You need to set the alwaysWriteExceptions to false in the pattern layout.
https://logging.apache.org/log4j/2.x/manual/layouts.html#PatternLayout
Then add to your pattern the throwable options you would like instead.
https://logging.apache.org/log4j/2.x/manual/layouts.html#Patterns
Outputs the Throwable trace bound to the LoggingEvent, by default this
will output the full trace as one would normally find with a call to
Throwable.printStackTrace().
You can follow the throwable conversion word with an option in the
form %throwable{option}.
%throwable{short} outputs the first line of the Throwable.
%throwable{short.className} outputs the name of the class where the
exception occurred.
%throwable{short.methodName} outputs the method name where the
exception occurred.
%throwable{short.fileName} outputs the name of the class where the
exception occurred.
%throwable{short.lineNumber} outputs the line number where the
exception occurred.
%throwable{short.message} outputs the message.
%throwable{short.localizedMessage} outputs the localized message.
%throwable{n} outputs the first n lines of the stack trace.
Specifying %throwable{none} or %throwable{0} suppresses output of the
exception.
If you still can not satisfy what you want with those options you would need to write a custom converter as described here.
https://logging.apache.org/log4j/2.x/manual/extending.html#PatternConverters
An example that is a little more clear then theirs.
#Plugin(name="HostNameConverter", category ="Converter")
#ConverterKeys({"h","host","hostName"})
public class HostNameConverter extends LogEventPatternConverter {
/**
* Constructs an instance of LoggingEventPatternConverter.
*
* #param name name of converter.
* #param style CSS style for output.
*/
protected HostNameConverter(String name, String style) {
super(name, style);
}
#Override
public void format(LogEvent event, StringBuilder toAppendTo) {
toAppendTo.append(HostNameUtil.getLocalHostName());
}
public static HostNameConverter newInstance(String[] options){
return new HostNameConverter(HostNameConverter.class.getSimpleName(),HostNameConverter.class.getSimpleName());
}
}
I think it's better: [...%m%n%ex]
I have an app using embedded Jetty. Everything works well, except for logging. I am now trying to use logback, but am getting fatal errors.
The app loads as you can see:
$ java -XX:+UseConcMarkSweepGC -XX:PermSize=64M -XX:MaxPermSize=256M -Xms1G -Xmx1G -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp -jar /usr/local/mexp/mexp.jar server /usr/local/mexp/mexp.json
10:46:02.093 [main] DEBUG org.eclipse.jetty.util.log - Logging to Logger[org.eclipse.jetty.util.log] via org.eclipse.jetty.util.log.Slf4jLog
10:46:02.098 [main] INFO org.eclipse.jetty.util.log - Logging initialized #76ms
followed by pages and pages of DEBUG statements describing loading of every class in my app. This suggests it is not finding the logback.xml, where I have set logging level for org.eclipse.jetty to ERROR.
Eventually, I am getting the following exceptions when the app loads:
10:46:30.349 [main] DEBUG o.e.jetty.webapp.WebAppClassLoader - loaded class org.slf4j.impl.StaticLoggerBinder from sun.misc.Launcher$AppClassLoader#659c2931
10:46:30.354 [main] WARN o.e.j.u.component.AbstractLifeCycle - FAILED o.e.j.w.WebAppContext#4e4e745{/,file:/usr/local/mexp/resources/webapp/,STARTING}{file:/usr/local/mexp/mexp.jar}: java.lang.LinkageError: loader constraint violation: when resolving method "org.slf4j.impl.StaticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory;" the class loader (instance of org/eclipse/jetty/webapp/WebAppClassLoader) of the current class, org/slf4j/LoggerFactory, and the class loader (instance of sun/misc/Launcher$AppClassLoader) for resolved class, org/slf4j/impl/StaticLoggerBinder, have different Class objects for the type LoggerFactory; used in the signature
java.lang.LinkageError: loader constraint violation: when resolving method "org.slf4j.impl.StaticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory;" the class loader (instance of org/eclipse/jetty/webapp/WebAppClassLoader) of the current class, org/slf4j/LoggerFactory, and the class loader (instance of sun/misc/Launcher$AppClassLoader) for resolved class, org/slf4j/impl/StaticLoggerBinder, have different Class objects for the type LoggerFactory; used in the signature
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:306) ~[mexp.jar:na]
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:276) ~[mexp.jar:na]
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:288) ~[mexp.jar:na]
at com.rc.util.logging.RCLog.<init>(RCLog.java:28) ~[mexp.jar:na]
at com.rc.commonwebapp.servlet.filter.SessionTXManager.<init>(SessionTXManager.java:43) ~[na:na]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.7.0_45]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) ~[na:1.7.0_45]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.7.0_45]
at java.lang.reflect.Constructor.newInstance(Constructor.java:526) ~[na:1.7.0_45]
at java.lang.Class.newInstance(Class.java:374) ~[na:1.7.0_45]
at org.eclipse.jetty.server.handler.ContextHandler$Context.createInstance(ContextHandler.java:2370) ~[mexp.jar:na]
at org.eclipse.jetty.servlet.ServletContextHandler$Context.createFilter(ServletContextHandler.java:1146) ~[mexp.jar:na]
at org.eclipse.jetty.servlet.FilterHolder.initialize(FilterHolder.java:120) ~[mexp.jar:na]
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:850) ~[mexp.jar:na]
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:298) ~[mexp.jar:na]
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1341) ~[mexp.jar:na]
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1334) ~[mexp.jar:na]
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:741) ~[mexp.jar:na]
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:497) ~[mexp.jar:na]
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68) [mexp.jar:na]
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132) [mexp.jar:na]
at org.eclipse.jetty.server.Server.start(Server.java:380) [mexp.jar:na]
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114) [mexp.jar:na]
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61) [mexp.jar:na]
at org.eclipse.jetty.server.Server.doStart(Server.java:347) [mexp.jar:na]
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68) [mexp.jar:na]
at com.pronto.JettyWebApp.main(JettyWebApp.java:95) [mexp.jar:na]
and
java.lang.LinkageError: loader constraint violation: when resolving method "org.slf4j.impl.StaticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory;" the class loader (instance of org/eclipse/jetty/webapp/WebAppClassLoader) of the current class, org/slf4j/LoggerFactory, and the class loader (instance of sun/misc/Launcher$AppClassLoader) for resolved class, org/slf4j/impl/StaticLoggerBinder, have different Class objects for the type LoggerFactory; used in the signature
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:306) ~[mexp.jar:na]
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:276) ~[mexp.jar:na]
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:288) ~[mexp.jar:na]
at com.rc.util.logging.RCLog.<init>(RCLog.java:28) ~[mexp.jar:na]
at com.rc.commonwebapp.servlet.filter.SessionTXManager.<init>(SessionTXManager.java:43) ~[na:na]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.7.0_45]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) ~[na:1.7.0_45]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.7.0_45]
at java.lang.reflect.Constructor.newInstance(Constructor.java:526) ~[na:1.7.0_45]
at java.lang.Class.newInstance(Class.java:374) ~[na:1.7.0_45]
at org.eclipse.jetty.server.handler.ContextHandler$Context.createInstance(ContextHandler.java:2370) ~[mexp.jar:na]
at org.eclipse.jetty.servlet.ServletContextHandler$Context.createFilter(ServletContextHandler.java:1146) ~[mexp.jar:na]
at org.eclipse.jetty.servlet.FilterHolder.initialize(FilterHolder.java:120) ~[mexp.jar:na]
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:850) ~[mexp.jar:na]
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:298) ~[mexp.jar:na]
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1341) ~[mexp.jar:na]
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1334) ~[mexp.jar:na]
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:741) ~[mexp.jar:na]
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:497) ~[mexp.jar:na]
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68) ~[mexp.jar:na]
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132) ~[mexp.jar:na]
at org.eclipse.jetty.server.Server.start(Server.java:380) ~[mexp.jar:na]
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114) ~[mexp.jar:na]
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61) ~[mexp.jar:na]
at org.eclipse.jetty.server.Server.doStart(Server.java:347) ~[mexp.jar:na]
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68) ~[mexp.jar:na]
at com.pronto.JettyWebApp.main(JettyWebApp.java:95) [mexp.jar:na]
Exception in thread "main" java.lang.LinkageError: loader constraint violation: when resolving method "org.slf4j.impl.StaticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory;" the class loader (instance of org/eclipse/jetty/webapp/WebAppClassLoader) of the current class, org/slf4j/LoggerFactory, and the class loader (instance of sun/misc/Launcher$AppClassLoader) for resolved class, org/slf4j/impl/StaticLoggerBinder, have different Class objects for the type LoggerFactory; used in the signature
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:306)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:276)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:288)
at com.rc.util.logging.RCLog.<init>(RCLog.java:28)
at com.rc.commonwebapp.servlet.filter.SessionTXManager.<init>(SessionTXManager.java:43)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at java.lang.Class.newInstance(Class.java:374)
at org.eclipse.jetty.server.handler.ContextHandler$Context.createInstance(ContextHandler.java:2370)
at org.eclipse.jetty.servlet.ServletContextHandler$Context.createFilter(ServletContextHandler.java:1146)
at org.eclipse.jetty.servlet.FilterHolder.initialize(FilterHolder.java:120)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:850)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:298)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1341)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1334)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:741)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:497)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
at org.eclipse.jetty.server.Server.start(Server.java:380)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
at org.eclipse.jetty.server.Server.doStart(Server.java:347)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at com.pronto.JettyWebApp.main(JettyWebApp.java:95)
Some web searching on java.lang.LinkageError suggests that Jetty and my app have different class loaders that are conflicting when trying to load LoggerFactory. I'm not sure what to do next.
ETA:
Per #PavelHoral's suggestion I added <scope>provided</scope> to my pom.xml (dependencyManagement section) but that results in this when I attempt to start the app:
2014-09-28 16:47:42.491:INFO::main: Logging initialized #66ms
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at com.rc.util.config.ConfigurationManager.<clinit>(ConfigurationManager.java:31)
at com.pronto.JettyWebApp.main(JettyWebApp.java:39)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 2 more
ETA: Per suggestion by #hd1 I added the bridge, which got rid of the LinkageError, so we're part way there. I'm still stymied by the fact that all of the logging goes to stdout and it's still at level DEBUG - not acceptable for a prod environment for sure, so I need to be able to configure this. Here is my logback.xml:
<configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>/usr/local/mexp/logs/mexp.service.log</file>
<encoder>
<pattern>"%-5p [%d{dd-MMM-yy HH:mm:ss}] [%t] %-20c %-3x:%m%n</pattern>
</encoder>
</appender>
<appender name="AXIS" class="ch.qos.logback.core.FileAppender">
<file>/usr/local/mexp/logs/axis.log</file>
<encoder>
<pattern>%-5p [%d{dd-MMM-yy HH:mm:ss}] :%m%n</pattern>
</encoder>
</appender>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!-- The default pattern: Date Priority [Category] Message\n -->
<encoder>
<pattern>%d{ABSOLUTE} %-5p [%c{1}] %m%n</pattern>
</encoder>
</appender>
<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
<appender-ref ref="AXIS"/>
</appender>
<logger name="org.apache">
<level value="ERROR"/>
</logger>
<logger name="org.quartz">
<level value="ERROR" />
</logger>
<logger name="org.hibernate">
<level value="ERROR" />
</logger>
<logger name="org.apache.struts.action">
<level value="INFO"/>
</logger>
<logger name="org.apache.catalina.cluster">
<level value="INFO"/>
</logger>
<logger name="org">
<level value="ERROR" />
</logger>
<logger name="net">
<level value="ERROR" />
</logger>
<logger name="org.apache.axis.transport.http.HTTPSender" additivity="false">
<level value="ERROR"/>
<appender-ref ref="ASYNC"/>
</logger>
<logger name="com.mchange">
<level value="ERROR"/>
</logger>
<!-- this silences the HttpClient chatter that starts with "httpclient.wire.header" and "httpclient.wire.content" -->
<logger name="org.apache.commons.httpclient">
<level value="fatal"/>
</logger>
<logger name="httpclient.wire.header">
<level value="fatal"/>
</logger>
<logger name="httpclient.wire.content">
<level value="fatal"/>
</logger>
<logger name="org.eclipse.jetty">
<level value="ERROR"/>
</logger>
<!-- Log the real SQL -->
<logger name="org.hibernate.SQL">
<level value="ERROR"/>
</logger>
<root level="ERROR">
<appender-ref ref="FILE"/>
</root>
</configuration>
ETA: I also tried the logging separation described here - added this to web.xml:
<env-entry>
<env-entry-name>logback/context-name</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>mexp</env-entry-value>
</env-entry>
and this in my jetty runner main method
System.setProperty("logback.ContextSelector", "JNDI");
(and changed the name of the logback file to logback-mexp.xml) but all of that results in no change in behavior.
We're definitely getting closer, but for the bounty I need the whole solution. Thanks!
ETA the current state of things. I no longer get the LinkageError. My app loads and performs fine. In fact there has been a considerable improvement in that now I don't get pages and pages of DEBUG lines in stdout. I still get all my logging in stdout, like so:
$ java -XX:+UseConcMarkSweepGC -XX:PermSize=64M -XX:MaxPermSize=256M -Xms1G -Xmx1G -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp -jar /usr/local/mexp/mexp.jar server /usr/local/mexp/mexp.json
Oct 01, 2014 3:54:28 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Oct 01, 2014 3:54:28 PM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Wed Oct 01 15:54:28 EDT 2014]; root of context hierarchy
Oct 01, 2014 3:54:28 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [mexpPapiContext.xml]
Oct 01, 2014 3:54:28 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 352 ms
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/usr/local/mexp/resources/webapp/WEB-INF/lib/slf4j-log4j12-1.7.7.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/local/mexp/mexp.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
15:54:28,596 INFO GlobalRootManager:85 - Entering initialization
15:54:28,840 INFO GlobalRootManager:85 - Exiting initialization
15:54:28,868 INFO FileUtil:220 - -> Found /mpds.properties in resource bundle
Oct 01, 2014 3:54:29 PM org.apache.struts.action.ActionServlet initChain
INFO: Loading chain catalog from jar:file:/usr/local/mexp/resources/webapp/WEB-INF/lib/struts-core-1.3.10.jar!/org/apache/struts/chain/chain-config.xml
Oct 01, 2014 3:54:29 PM org.apache.struts.action.ActionServlet initChain
INFO: Loading chain catalog from jar:file:/usr/local/mexp/mexp.jar!/org/apache/struts/chain/chain-config.xml
Oct 01, 2014 3:54:29 PM org.apache.struts.validator.ValidatorPlugIn initResources
INFO: Loading validation rules file from '/WEB-INF/struts/validator-rules.xml'
Oct 01, 2014 3:54:29 PM org.apache.struts.validator.ValidatorPlugIn initResources
INFO: Loading validation rules file from '/WEB-INF/struts/validation-mexp.xml'
15:54:29,529 INFO QuartzStartupServlet:85 - Entering servlet init.
15:54:29,562 INFO StdSchedulerFactory:1184 - Using default implementation for ThreadExecutor
15:54:29,575 INFO SchedulerSignalerImpl:61 - Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
15:54:29,575 INFO QuartzScheduler:240 - Quartz Scheduler v.2.2.1 created.
15:54:29,576 INFO XMLSchedulingDataProcessorPlugin:200 - Registering Quartz Job Initialization Plug-in.
15:54:29,578 INFO RAMJobStore:155 - RAMJobStore initialized.
15:54:29,578 INFO QuartzScheduler:305 - Scheduler meta-data: Quartz Scheduler (v2.2.1) 'MexpScheduler' with instanceId 'dev'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 5 threads.
Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.
15:54:29,578 INFO StdSchedulerFactory:1339 - Quartz scheduler 'MexpScheduler' initialized from an externally provided properties instance.
15:54:29,578 INFO StdSchedulerFactory:1343 - Quartz scheduler version: 2.2.1
15:54:29,592 INFO XMLSchedulingDataProcessor:471 - Parsing XML file: mexp-dev-jobs.xml with systemId: mexp-dev-jobs.xml
15:54:29,948 INFO XMLSchedulingDataProcessor:996 - Adding 13 jobs, 13 triggers.
15:54:29,949 INFO XMLSchedulingDataProcessor:1034 - Adding job: skuLevelBiddingReportGroup.skuLevelBiddingReportJob
15:54:29,951 INFO XMLSchedulingDataProcessor:1034 - Adding job: emailNotificationsGroup.emailNotificationsJob
15:54:29,952 INFO XMLSchedulingDataProcessor:1034 - Adding job: balanceReplenishmentGroup.balanceReplenishmentJob
15:54:29,953 INFO XMLSchedulingDataProcessor:1034 - Adding job: balanceReplenishmentCappedInvoiceGroup.balanceReplenishmentCappedInvoiceJob
15:54:29,954 INFO XMLSchedulingDataProcessor:1034 - Adding job: merchantTxnProcessingGroup.merchantTxnProcessingJob
15:54:29,956 INFO XMLSchedulingDataProcessor:1034 - Adding job: feedFileManagerGroup.feedFileManagerJob
15:54:29,957 INFO XMLSchedulingDataProcessor:1034 - Adding job: merchantPaymentManagerGroup.merchantPaymentManagerJob
15:54:29,958 INFO XMLSchedulingDataProcessor:1032 - Replacing job: merchantTxnProcessingGroup.merchantTxnProcessingJob
15:54:29,958 INFO XMLSchedulingDataProcessor:1034 - Adding job: expiredAccountUpdaterGroup.expiredAccountUpdaterJob
15:54:29,959 INFO XMLSchedulingDataProcessor:1034 - Adding job: placementsForDatasyncUpdaterGroup.placementsForDatasyncUpdaterJob
15:54:29,960 INFO XMLSchedulingDataProcessor:1034 - Adding job: placementPaymentProcessingGroup.placementPaymentProcessingJob
15:54:29,961 INFO XMLSchedulingDataProcessor:1034 - Adding job: switchingMerchantsToInvoiceGroup.switchingMerchantsToInvoiceJob
15:54:29,962 INFO XMLSchedulingDataProcessor:1034 - Adding job: toggleActiveStateGroup.toggleActiveStateJob
15:54:29,963 INFO QuartzScheduler:575 - Scheduler MexpScheduler_$_dev started.
15:54:29,982 INFO LoggingTriggerHistoryPlugin:387 - Trigger JobSchedulingDataLoaderPlugin.JobSchedulingDataLoaderPlugin_jobInitializer_mexp-dev-jobs_xml fired job JobSchedulingDataLoaderPlugin.JobSchedulingDataLoaderPlugin_jobInitializer_mexp-dev-jobs_xml at: 15:54:29 10/01/2014
15:54:29,983 INFO LoggingJobHistoryPlugin:469 - Job JobSchedulingDataLoaderPlugin.JobSchedulingDataLoaderPlugin_jobInitializer_mexp-dev-jobs_xml fired (by trigger JobSchedulingDataLoaderPlugin.JobSchedulingDataLoaderPlugin_jobInitializer_mexp-dev-jobs_xml) at: 15:54:29 10/01/2014
15:54:29,984 INFO LoggingJobHistoryPlugin:513 - Job JobSchedulingDataLoaderPlugin.JobSchedulingDataLoaderPlugin_jobInitializer_mexp-dev-jobs_xml execution complete at 15:54:29 10/01/2014 and reports: null
15:54:29,984 INFO LoggingTriggerHistoryPlugin:433 - Trigger JobSchedulingDataLoaderPlugin.JobSchedulingDataLoaderPlugin_jobInitializer_mexp-dev-jobs_xml completed firing job JobSchedulingDataLoaderPlugin.JobSchedulingDataLoaderPlugin_jobInitializer_mexp-dev-jobs_xml at 15:54:29 10/01/2014 with resulting trigger instruction code: DO NOTHING
Please see this page on the slf4j site. I suspect you've not included the appropriate bridge jar. For example, for log4j, you're going to need the following stanzas in your pom.xml:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
Hope that helps. If not, feel free to leave a comment.
I do not think there is a silver bullet here: logging in Java takes many forms and it takes attention to detail to get it right. Especially when class-loaders come in to play as is the case with web-apps.
The explanation about how logging works with Slf4j by Joakim Erdfelt is pretty good (I saw this in the mail-conversation you had with him earlier).
I can only add to do a proper clean-up:
put the jar-files for Logback, the Slf4j-api and the required Slf4j-bridges (jcl-over-slf4j, log4j-over-slf4j) in the main/common/launch class-path.
remove everything else that has anything to do with logging (log4j, commons-logging, etc.). The "dependencyManagement with scope provided" trick mentioned in the comments by Pavel Horal can come in handy here.
for some components you need to programmatically set Slf4j as logger, e.g. for Hibernate 4.3 use System.setProperty("org.jboss.logging.provider", "slf4j"); before Hibernate is started.
if Slf4j cannot be set as logger for a component, try setting Log4j. The slf4j-bridge "log4j-over-slf4j" will redirect the logging from Log4j to Slf4j and Slf4j will send it to the logging implementation (Logback). Note that you only need the bridge jar-file "log4j-over-slf4j" and NOT the log4j-jar (the bridge will provide replacements for the Log4j classes) in your main class-path.
You should now have only one jar-file and/or class in your entire assembly for your application for each logging related component mentioned in the first point of the clean-up. Double check that there are no logging related jar-files in any of the web-apps (WEB-INF/lib folders). On a side node: if you use JDBC-drivers, follow the same procedure (these tend to give trouble as well if they are not in the main class-path).
Before you start the clean-up you should verify your basic setup by using Logback with the Jetty embedded Hello World example.
It takes some effort to get all this logging going but, as you said, it is required for production and it has helped me during development: simply switching on trace/debugging for a third-party component (via a logger-category in logback-test.xml) can provide a lot of insight in what is happening (especially when combined with unit-tests).
I had this proble. Turns out I found an embarrasingly easy sollution (in my case).
Jetty didn't find my slf4j-*.jar(s) unless I added them as dependencies to the plugin configuration itself. I will not include my entire pom.xml but merely the plugin conf. Hope this helps.
Cheers
...
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.1.10.v20130312</version>
<configuration>
<webAppConfig>
</webAppConfig>
</configuration>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.codehaus.fabric3</groupId>
<artifactId>fabric3-atomikos-library</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.codehaus.btm</groupId>
<artifactId>btm-jetty6-lifecycle</artifactId>
<version>1.3.3</version>
</dependency>
</dependencies>
</plugin>
...
I then checked the project dependency tree using the Maven Dependency Plugin and removed/excluded all unwanted logging frameworks included by dependencies and it worked.