Can't Create RollingFileAppender with System property variable - java

While creating RollingFileAppender with a System property variable I got the following error.
ERROR Unable to invoke factory method in class class org.apache.logging.log4j.core.appender.RollingFileAppender for element RollingFile. java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.build(PluginBuilder.java:132)
at org.apache.logging.log4j.core.config.AbstractConfiguration.createPluginObject(AbstractConfiguration.java:918)
at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:858)
at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:850)
at org.apache.logging.log4j.core.config.AbstractConfiguration.doConfigure(AbstractConfiguration.java:479)
at org.apache.logging.log4j.core.config.AbstractConfiguration.initialize(AbstractConfiguration.java:219)
at org.apache.logging.log4j.core.config.AbstractConfiguration.start(AbstractConfiguration.java:231)
at org.apache.logging.log4j.core.LoggerContext.setConfiguration(LoggerContext.java:496)
at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:566)
at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:582)
at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:217)
at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:152)
at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:45)
at org.apache.logging.log4j.LogManager.getContext(LogManager.java:194)
at org.apache.logging.log4j.LogManager.getLogger(LogManager.java:551)
at com.hifx.lens.services.AvroSerializerFactory.<init>(AvroSerializerFactory.java:16)
at com.hifx.lens.services.AvroSerializerFactory.init(AvroSerializerFactory.java:43)
at com.hifx.lens.Accumulo.main(Accumulo.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.lang.ClassCastException: org.apache.logging.log4j.core.appender.FileManager cannot be cast to org.apache.logging.log4j.core.appender.rolling.RollingFileManager
at org.apache.logging.log4j.core.appender.rolling.RollingFileManager.getFileManager(RollingFileManager.java:103)
at org.apache.logging.log4j.core.appender.RollingFileAppender.createAppender(RollingFileAppender.java:191)
... 27 more
My log4j2.yml configuration file is
Configutation:
name: Default
Properties:
Property:
name: LOG_PATH
value: "logs"
Appenders:
Console:
name: Console_Appender
target: SYSTEM_OUT
PatternLayout:
pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"
File:
name: File_Appender
fileName: ${sys:LOG_PATH}/log.log
PatternLayout:
pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"
RollingFile:
name: RollingFile_Appender
fileName: ${sys:LOG_PATH}/log.log
filePattern: "logs/archive/rollingfile.log.%d{yyyy-MM-dd-hh-mm}.gz"
PatternLayout:
pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"
Policies:
SizeBasedTriggeringPolicy:
size: 100 KB
DefaultRollOverStrategy:
max: 30
Loggers:
Root:
level: debug
AppenderRef:
- ref: RollingFile_Appender
Logger:
- name: Accumulo_File_logger
level: debug
AppenderRef:
- ref: File_Appender
If I change the filename of RollingFile_Appender to using property name ie:
fileName: ${LOG_PATH}/log.log
then the error is disappeared and everything working fine.
If I use the File_Appender( which is also using the same System property variable(sys:LOG_PATH)) then also everything working fine.
Same error if I change sys: to env:
I think there is some parsing issue with the jackson.
I need to configure the log path from environment variables.
Dependencies using are
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-jcl</artifactId>
<version>2.6.2</version>
</dependency>
Somebody please help me

This is because you defined both File_Appender and RollingFile_Appender to log into the same file. They kind of "own" their log files, so once a File appender has been created for the ${sys:LOG_PATH}/log.log you cannot create a RollingFile appender pointing to the same file. The second appender in the configuration file tries to create a LogManager that would be responsible for the file, finds the first one being already there so tries to cast into the class that it needs - and fails.
If you move the RollingFile_Appender above File_Appender the exception will be:
main ERROR Unable to invoke factory method in class class org.apache.logging.log4j.core.appender.FileAppender for element File. java.lang.reflect.InvocationTargetException
Now the RollingFile_Appender would own the ${sys:LOG_PATH}/log.log file and you wouldn't be able to create the File_Appender because of the same reason.
Solution: remove one of the appenders, having both at the same time doesn't make sense anyway - they would have to compete with each other, or point each of the to a different file.

Related

Log4j does literally nothing?

My configuration file is path of the class path. At least I thought it is. I placed the log4j.properties file in the resources folder and log4j does nothing with it. Even if I delete it, no error occurs.
As anyone can see I'm using maven
Content of LoggerTest:
package com.dersimi.stella.logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LoggerTest {
public static void main(String[] args) {
System.out.println("xxx");
Logger logger = LogManager.getLogger(LoggerTest.class);
logger.info("Hello this is an info message");
System.out.println("xxx");
}
}
Program output:
xxx
xxx
Content of log4j.properties:
log4j.rootLogger=INFO, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=INFO
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %m%n
In pom.xml is nothing out of the ordinary, just the dependency org.apache.logging.log4j log4j-core 2.17.2, compiler source target is 16, no plugins
The main problem is that you are trying to use log4j (the first one) configurations for log4j2.
In first place make sure you have the following dependencies:
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.0</version>
</dependency>
Second, have a file named log4j2.properties with a content like this:
status = warn
appender.console.type = Console
appender.console.name = LogToConsole
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
rootLogger.level = info
rootLogger.appenderRef.stdout.ref = LogToConsole
Reference: https://mkyong.com/logging/log4j2-properties-example/

Selenium - Exception in thread "main" java.lang.NoClassDefFoundError: org/reactivestreams/Publisher

I am creating a Maven project for Selenium in eclipse. Don't know why it threw log4j error (It didn't used to earlier, before upgrading Eclipse). The error is as follows -
I have already added "log4j.properties" file under src/main/resources as -
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Also added dependency as following in POM.xml -
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.26</version>
</dependency>
Artifacts used -
Eclipse - Version: 2020-06 (4.16.0)
Maven artifact id - maven-archetype-quickstart - v1.4
Selenium version - 3.141.59
The error is not related to log4j. The error is for org.reactivestreams.Publisher. Add the following Maven dependency to get it:
<!-- https://mvnrepository.com/artifact/org.reactivestreams/reactive-streams -->
<dependency>
<groupId>org.reactivestreams</groupId>
<artifactId>reactive-streams</artifactId>
<version>1.0.3</version>
</dependency>
Make sure to update the project after adding the dependency.

Failed to load class org.slf4j.impl.StaticLoggerBinder even though StaticLoggerBinder is in Maven-Rep

I'm trying to use the slf4j-Logger-Functions but always getting the same error:
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.
I already tried the common solutions and as you can see in the image, the "StaticLoggerBinder" is loaded into the directory but the error still excists. Do you have any idea why?
package de.stefan.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Test {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(Test.class);
logger.info("This is how you configure Java Logging with SLF4J");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>de.stefan</groupId>
<artifactId>stefan</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
</dependency>
</dependencies>
</project>
Project structure
slf4j-simple is not your classpath when you ran the program. Put it in your classpath, something like java -classpath ./lib/* YourProgram. Where lib contains your jar files.
Just make sure you have following 4j dependencies in pom, and add log4j.properties/xml with required appanders i.e. for Console or/and file in your class path .
Mention the the version in properties as per your needs, recent is better-
<log4j.version>2.13.3</log4j.version>
<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-slf4j-impl</artifactId>
<version>${log4j.version}</version>
<scope>runtime</scope>
</dependency>
A sample Log4j Config Properties file can be like this-
status = error
name= properties_configuration
# Give directory path where log files should get stored
#property.basePath = E:\\AppTest_logs\\
# ConsoleAppender will print logs on console
appender.console.type = Console
appender.console.name = consoleLogger
appender.console.target = SYSTEM_OUT
appender.console.layout.type = PatternLayout
appender.file.type = File
appender.file.name = STDOUT
appender.file.filename = logs/AppsConsole.log
appender.file.layout.type = PatternLayout
appender.console.filter.threshold.type = ThresholdFilter
appender.console.filter.threshold.level = error
# Specify the pattern of the logs
appender.console.layout.pattern = %highlight{ [%p] %d{dd MMM yyyy HH:mm:ss,SSS} [%t] %x %c %M - %m%n}{FATAL=white, ERROR=Blink red, WARN=Underline yellow, INFO=Bright white, DEBUG=Bright green, TRACE=blue}
appender.file.layout.pattern = %d{yyyy-MM-dd}-%t-%x-%-5p-%-10c:%m%n
# RollingFileAppender will print logs in file which can be rotated based on time or size
# Mention package name here in place of example. Classes in this package or subpackages will use ConsoleAppender and RollingFileAppender for logging
logger.example.name = com.threeylos.zapizook
logger.example.level = info
logger.example.additivity = false
logger.example.appenderRef.rolling.ref = fileLogger
logger.example.appenderRef.console.ref = consoleLogger
# Configure root logger for logging error logs in classes which are in package other than above specified package
rootLogger.level = info
rootLogger.additivity = false
#rootLogger.appenderRef.rolling.ref = fileLogger
rootLogger.appenderRef.console.ref = consoleLogger

What version of log4j did %c{1.} become valid

I would like to use the following Conversion Pattern
%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1.}:%L - %m%n
Which produces output like
2016-06-08 10:29:40 [http-nio-8080-exec-8] DEBUG h.d.h.l.l.s.w.f.MyClass:27 - This is a debug message.
2016-06-08 10:29:40 [http-nio-8080-exec-8] INFO h.d.h.l.l.s.w.f.MyClass:22 - This is an info message.
2016-06-08 10:29:40 [http-nio-8080-exec-8] WARN h.d.h.l.l.s.w.f.MyClass:33 - This is a warn message.
2016-06-08 10:29:40 [http-nio-8080-exec-8] ERROR h.d.h.l.l.s.w.f.MyClass:39 - This is an error message.
2016-06-08 10:29:40 [http-nio-8080-exec-8] FATAL h.d.h.l.l.s.w.f.MyClass:45 - This is a fatal message.
However when I run my tests and trigger my log4j file I get the error message
log4j:ERROR Category option "1." not a decimal integer.
Log4j and slf4j are setup in my pom with
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.19</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.19</version>
<scope>runtime</scope>
</dependency>
What version of log4j do I need to get 1. to be a valid Category option.
I was using PatternLayout not EnhancedPatternLayout
%c{1.}
Is only available in EnhancedPatternLayout

slf4j - logback NullPointer in Spring MVC tests

I am running some unit tests and I was to use SLF4J and logback.
Here is the relevant pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.6-RELEASE</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
And here is the log and stacktrace:
20:29:16,293 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback-test.xml] at [file:/code/web/target/test-classes/logback-test.xml]
20:29:16,387 |-ERROR in ch.qos.logback.core.joran.event.SaxEventRecorder#7a1ebcd8 - Unexpected exception while parsing XML document. java.lang.NullPointerException
at java.lang.NullPointerException
at at org.xml.sax.helpers.LocatorImpl.<init>(LocatorImpl.java:103)
at at ch.qos.logback.core.joran.event.SaxEvent.<init>(SaxEvent.java:31)
at at ch.qos.logback.core.joran.event.StartEvent.<init>(StartEvent.java:27)
at at ch.qos.logback.core.joran.event.SaxEventRecorder.startElement(SaxEventRecorder.java:106)
at at org.allcolor.xml.parser.CShaniSaxParser.parseStartTag(CShaniSaxParser.java:1393)
at at org.allcolor.xml.parser.CXmlParser.parseSTARTTag(CXmlParser.java:1405)
at at org.allcolor.xml.parser.CXmlParser.parse(CXmlParser.java:682)
at at org.allcolor.xml.parser.CShaniSaxParser.parse(CShaniSaxParser.java:767)
at at javax.xml.parsers.SAXParser.parse(SAXParser.java:392)
at at ch.qos.logback.core.joran.event.SaxEventRecorder.recordEvents(SaxEventRecorder.java:59)
at at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:141)
at at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:103)
at at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:53)
at at ch.qos.logback.classic.util.ContextInitializer.configureByResource(ContextInitializer.java:75)
at at ch.qos.logback.classic.util.ContextInitializer.autoConfig(ContextInitializer.java:150)
at at org.slf4j.impl.StaticLoggerBinder.init(StaticLoggerBinder.java:84)
at at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:55)
at at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
at at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
at at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:412)
at at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:357)
at at org.apache.commons.logging.impl.SLF4JLogFactory.getInstance(SLF4JLogFactory.java:155)
at at org.apache.commons.logging.impl.SLF4JLogFactory.getInstance(SLF4JLogFactory.java:132)
at at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:685)
at at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<clinit>(SpringJUnit4ClassRunner.java:91)
at at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
And the logback-test.xml:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<Pattern>.%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg %n
</Pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>TRACE</level>
</filter>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="consoleAppender" />
</root>
<logger name="com.me.ControllerTester" level="debug" additivity="false">
<appender-ref ref="consoleAppender" />
</logger>
</configuration>
Now I have checked the dependency tree, and I have nothing conflicting. I have tried messing with the SAX parser versions.
The XML looks fine to me. I must be conflicted somehow...
Any Ideas?
logback uses SAXParserFactory.newInstance(), which has a lookup procedure that determines which implementation to use. It seems that org.allcolor.xml.parser.CShaniSaxParser is being selected in your environment based on this lookup:
public static SAXParserFactory newInstance()
Obtain a new instance of a SAXParserFactory. This static method creates a new factory instance This method uses the following ordered lookup procedure to determine the SAXParserFactory implementation class to load:
Use the javax.xml.parsers.SAXParserFactory system property.
Use the properties file "lib/jaxp.properties" in the JRE directory. This configuration file is in standard java.util.Properties format and contains the fully qualified name of the implementation class with the key being the system property defined above. The jaxp.properties file is read only once by the JAXP implementation and it's values are then cached for future use. If the file does not exist when the first attempt is made to read from it, no further attempts are made to check for its existence. It is not possible to change the value of any property in jaxp.properties after it has been read for the first time.
Use the Services API (as detailed in the JAR specification), if available, to determine the classname. The Services API will look for a classname in the file META-INF/services/javax.xml.parsers.SAXParserFactory in jars available to the runtime.
Platform default SAXParserFactory instance.
Once an application has obtained a reference to a SAXParserFactory it can use the factory to configure and obtain parser instances.
Tip for Trouble-shooting
Setting the jaxp.debug system property will cause this method to print a lot of debug messages to System.err about what it is doing and where it is looking at.
If you have problems loading DocumentBuilders, try:
java -Djaxp.debug=1 YourProgram ....
Try switching to a standard SAX parser (such as Apache Xerces) by setting javax.xml.parsers.SAXParserFactory system property for your unit tests:
-Djavax.xml.parsers.SAXParserFactory=org.apache.xerces.jaxp.SAXParserFactoryImpl

Categories