How to convert the log4j.properties file to log4j2.properties file [duplicate] - java

I have a Java application which is using log4j configured as below.
log4j.properties:
log4j.rootLogger=INFO, R
log4j.appender.R = org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File = /trace.log
log4j.appender.R.Append = true
log4j.appender.R.DatePattern = '.'yyyy-MM-dd
log4j.appender.R.layout = org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern = %d{HH:mm:ss} %c{1} [%p] %m%n
I would like to migrate to log4j2 with the same configuration as above. Haven't found anything related to log4j2 properties configuration file as this support recently included.
How would be my log4j2.properties file with the same configuration above ?

Here is what I constructed after going through the documentation and worked.
rootLogger.level = INFO
property.filename = trace.log
appenders = R, console
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d %5p [%t] (%F:%L) - %m%n
appender.R.type = RollingFile
appender.R.name = File
appender.R.fileName = ${filename}
appender.R.filePattern = ${filename}.%d{yyyy-MM-dd}
appender.R.layout.type = PatternLayout
appender.R.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n
appender.R.policies.type = Policies
appender.R.policies.time.type = TimeBasedTriggeringPolicy
appender.R.policies.time.interval = 1
rootLogger.appenderRefs = R, console
rootLogger.appenderRef.console.ref = STDOUT
rootLogger.appenderRef.R.ref = File

You can use this to convert from Log4J.properties (v1.2) to log4j2.xml as below:
1) Convert from v1.2 properties to v1.2XML using this converter: https://log4j-props2xml.appspot.com/
2) Convert from v1.2 XML to v2.0 XML (i.e. Log4j2.xml) using the procedure provided on this link: https://logging.apache.org/log4j/2.x/manual/migration.html

Log4j2 supports .properties files but they have changed property syntax. You can check their manual here it covers all you need to create new configuration.

I know it's an old issue but for the sake of history:
Since Log4j2 2.13.0 there is an experimental feature for Log4j 1 configuration files:
http://logging.apache.org/log4j/2.x/manual/compatibility.html
Related JIRA issue:
https://issues.apache.org/jira/browse/LOG4J2-63

You can use this wonderful frontend web to convert you properties to a XML
http://log4j-props2xml.appspot.com/
Resulting:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="R" class="org.apache.log4j.DailyRollingFileAppender">
<param name="Append" value="true"/>
<param name="DatePattern" value="'.'yyyy-MM-dd"/>
<param name="File" value="/trace.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{HH:mm:ss} %c{1} [%p] %m%n"/>
</layout>
</appender>
<root>
<level value="INFO"/>
<appender-ref ref="R"/>
</root>
</log4j:configuration>

Related

Log4j2.xml configuration doesn't work but log4j2.properties does

Hello I have this problem were if i use a log4j2.xml file as a configuration file the logger won't log to console, whereas if i am using a .properties file instead i will have the logs in file.
This is the .xml file
<?xml version="1.0" encoding="UTF-8"?>
<!-- Extra logging related to initialization of Log4j.
Set to debug or trace if log4j initialization is failing. -->
<Configuration status="warn">
<Appenders>
<!-- Console appender configuration -->
<Console name="console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
</Console>
</Appenders>
<Loggers>
<!-- Root logger referring to console appender -->
<Root level="info" additivity="false">
<AppenderRef ref="console" />
</Root>
</Loggers>
</Configuration>
.properties file:
# Set to debug or trace if log4j initialization is failing
status = warn
# Name of the configuration
name = ConsoleLogConfigDemo
# Console appender configuration
appender.console.type = Console
appender.console.name = consoleLogger
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Root logger level
rootLogger.level = debug
# Root logger referring to console appender
rootLogger.appenderRef.stdout.ref = consoleLogger
(I am trying to do this for a migration from log4j to log4j2 and if i am using the .properties file everything seems to work)
I had the properties file and xml file both in resources folder.

why is my log file empty when I use log4j2?

please help me debug something-- I am getting an empty log file when I use log4j2.
Here is my log4j2.properties file:
# Root logger option
name=PropertiesConfig
property.filename = logs
appenders = stdout, file
# stdout will print logs on console
appender.stdout.name = consoleLogger
appender.stdout.type = Console
appender.stdout.target = System.out
appender.stdout.layout.type = PatternLayout
appender.stdout.layout.pattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# file will print logs in file
appender.file.name = fileLogger
appender.file.type = File
appender.file.fileName=ProtScannerLog.log
appender.file.layout.type = PatternLayout
appender.file.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
loggers=file
logger.file.name = log4j2.properties
logger.file.level = info
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = fileLogger
rootLogger.level = info
rootLogger.appenderRefs = stdout, file
rootLogger.appenderRef.stdout.ref = consoleLogger
rootLogger.appenderRef.file.ref = fileLogger
# added for debugging
# logs the SQL statements
log4j.logger.org.hibernate.SQL=DEBUG
# Logs the JDBC parameters passed to a query
log4j.logger.org.hibernate.type=TRACE
log4j.appender.hb=org.apache.log4j.ConsoleAppender
log4j.appender.hb.layout=org.apache.log4j.PatternLayout
And my log4j2.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<File name="File" fileName="ProtScannerLog.log" append="true">
<PatternLayout pattern="%d %t %-5p %c{2} - %m%n"/>
</File>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console" level="info" />
<AppenderRef ref="File" level="error" />
</Root>
</Loggers>
</Configuration>
When I run I get the log file in the directory I am running my code from, but it is blank. I see the correct messages in the console. I also would like to have this log file placed in C:\Users\username, but I am having trouble specifying that location. Any help would be much appreciated. Thanks in advance.
It supposed to be comment, but I don't have a reputation so have to post it this way :)
I've just copy pasted your config and it generated the ProtScannerLog.log file with several lines in.
So it definitely not log4j2.properties config issue.
Regarding the location of the file I can suggest to replace:
property.filename = logs
by
property.filename = C:\\Users\\username
And then refer to the property in "appender.file.fileName" definition:
appender.file.fileName=${filename}\\ProtScannerLog.log
It would create the file under any folder you specify.

org.slf4j.Logger logs to console, how do I log to file?

I am using the org.slf4j.Logger to log output. Output is going to console. How do I get logging logged to a log file?
private static final Logger LOG = LoggerFactory.getLogger(ClassName.class );
LOG.info("Logging output to console");
I am not using a log4j.properties file. I am assuming I will need one.
I added the following log4j.properties file and placed it in different parts of my eclipse project.
# Define the file appender
log4j.appender.FileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.FileAppender.File=logger.log
log4j.appender.FileAppender.layout = org.apache.log4j.PatternLayout
log4j.appender.FileAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
# Direct all messages there
log4j.rootLogger = INFO, FileAppender
I even used
PropertyConfigurator.configure("log4j.properties");
But no logging file appears. log4j.properties doesn't seem to have an effect.
The simplest way, I think, is to define a FileAppender in a log4j.properties file:
# Define the file appender
log4j.appender.FileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.FileAppender.File=[log filename].log
log4j.appender.FileAppender.layout = org.apache.log4j.PatternLayout
log4j.appender.FileAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
# Direct all messages there
log4j.rootLogger = INFO, FileAppender
Just replace [log filename] with some relevant filename. I think Log4j is able to automatically locate the file when you run the project from Eclipse if the file is in your project directory, but I'm not 100% sure. You can use PropertyConfigurator at the start of your application to tell Log4j where to find the properties file, e.g.:
PropertyConfigurator.configure("log4j.properties");
You can create a log4j.xml in the resource folder.
Import log4j package in the class.
Inside the class, instantiate a logger object using Logger.getLogger( ) static method.
Instantiate layouts (readymade or user-defined) to be assigned to appenders.
Instantiate appenders and assign desired layout to them by passing the layout object as parameter to their constructors.
Assign the instatiated appenders to the Logger object by invoking its addAppender( ) method with desired appender as parameter.
Invoke appropriate printing methods on Logger object to perform logging.
.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%p [%t] %c{1}.%M(%L) | %m%n" />
</layout>
</appender>
<appender name="FILE" class="org.apache.log4j.rolling.RollingFileAppender">
<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="fileNamePattern" value="/yourfolder/debug_%d{dd-MM-yy}.log" />
</rollingPolicy>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%p [%t] %c{1}.%M(%L) | %m%n" />
</layout>
</appender>
<root>
<level value="WARN" />
<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
</root>
</log4j:configuration>

Create log file with date using log4j

I'm writing my log file using below code but it stores file as QueryLog.log. Am i missing something? Check my code of log4j.properties file
log4j.logger.org.hibernate=INFO
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
log4j.logger.org.hibernate.hql.ast.AST=info
log4j.logger.org.hibernate.tool.hbm2ddl=warn
log4j.logger.org.hibernate.hql=debug
log4j.logger.org.hibernate.cache=info
log4j.logger.org.hibernate.jdbc=debug
log4j.rootLogger = DEBUG, FILE
log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender
log4j.appender.FILE.DatePattern='.'yyyy-MM-dd-a
log4j.appender.FILE.File=log4j/QueryLog.log
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern= %d{HH:mm:ss} %-5p %c - %m%n
Links i used:
http://www.tutorialspoint.com/log4j/log4j_logging_files.htm
http://www.codejava.net/coding/configure-log4j-for-creating-daily-rolling-log-files
As is mentioned in this StackOverflow Q&A, the purpose of a RollingFileAppender is to automatically create a new log file at some defined interval. In the case of the DailyRollingFileAppender, that interval is 12:00 AM of each day.
What this means is that the first file created by log4j will have the file name you specified here:
log4j.appender.FILE.File=log4j/QueryLog.log
And, from then forward, each day a new log file will be created with the date appended to it.
To always name the file with the date appended, you could use DatedFileAppender by Geoff Mottram
This line sets the log file name, in your log4j properties you have:
log4j.appender.FILE.File=log4j/QueryLog.log
You can see the answer here
Setting a log file name to include current date in Log4j
The solution to log directly to a file with current active date/time such as XYZ.log.20150101.log instead of XYZ.log could be done by simply removing ActiveFileName property when using the rolling package org.apache.log4j.rolling.RollingFileAppender in the apache-log4j-extras 1.1 with log4j 1.2.x.
<appender name="defaultFileAppender" class="org.apache.log4j.rolling.RollingFileAppender">
<param name="append" value="true" />
<param name="Threshold" value="INFO" />
<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="FileNamePattern"
value="${catalina.base}/logs/application/custom-application-logger.%d{yyyy-MM-dd_HH_mm}" />
</rollingPolicy>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %-10t [%-40.40c] %x - %m%n" />
</layout>
</appender>

Configuring RollingFileAppender in log4j

I'm working on a set of web services and we'd like to have a daily rotated log.
I'm trying to get org.apache.log4j.rolling.RollingFileAppender from the log4j extras companion working, since the documentation suggests this is best for production environments.
I have both the main log4J library (log4j-1.2.15.jar) and the log4j extras library (apache-log4j-extras-1.1.jar) on the classpath.
I have the following configuration for the appender in the log4j.properties file:
### SOAP Request Appender
log4j.appender.request=org.apache.log4j.rolling.RollingFileAppender
log4j.appender.request.File=SOAPmessages.log
log4j.appender.request.RollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.request.RollingPolicy.ActiveFileName =SOAPmessages-%d.log
log4j.appender.request.RollingPolicy.FileNamePattern=SOAPmessages-%d.log.zip
log4j.appender.request.layout = org.apache.log4j.PatternLayout
log4j.appender.request.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
However, when I start the web service with log4j in debug mode I get these error messages:
log4j: Parsing appender named "request".
log4j: Parsing layout options for "request".
log4j: Setting property [conversionPattern] to [%d{ABSOLUTE} %5p %c{1}:%L - %m%n].
log4j: End of parsing for "request".
log4j: Setting property [file] to [/logs/SOAPmessages.log].
log4j:WARN Failed to set property [rollingPolicy] to value "org.apache.log4j.rolling.TimeBasedRollingPolicy".
log4j:WARN Please set a rolling policy for the RollingFileAppender named 'request'
log4j: Parsed "request" options.
I've found documentation about how to configure this appender a little sparse, so can anyone help me fix my configuration?
EDIT0: Added debug mode output, rather than just the standard warnings
I had a similar problem and just found a way to solve it (by single-stepping through log4j-extras source, no less...)
The good news is that, unlike what's written everywhere, it turns out that you actually CAN configure TimeBasedRollingPolicy using log4j.properties (XML config not needed! At least in versions of log4j >1.2.16 see this bug report)
Here is an example:
log4j.appender.File = org.apache.log4j.rolling.RollingFileAppender
log4j.appender.File.rollingPolicy = org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.File.rollingPolicy.FileNamePattern = logs/worker-${instanceId}.%d{yyyyMMdd-HHmm}.log
BTW the ${instanceId} bit is something I am using on Amazon's EC2 to distinguish the logs from all my workers -- I just need to set that property before calling PropertyConfigurator.configure(), as follow:
p.setProperty("instanceId", EC2Util.getMyInstanceId());
PropertyConfigurator.configure(p);
Faced more issues while making this work. Here are the details:
To download and add apache-log4j-extras-1.1.jar in the classpath, didn't notice this at first.
The RollingFileAppender should be org.apache.log4j.rolling.RollingFileAppender instead of org.apache.log4j.RollingFileAppender. This can give the error: log4j:ERROR No output stream or file set for the appender named [file].
We had to upgrade the log4j library from log4j-1.2.14.jar to log4j-1.2.16.jar.
Below is the appender configuration which worked for me:
<appender name="file" class="org.apache.log4j.rolling.RollingFileAppender">
<param name="threshold" value="debug" />
<rollingPolicy name="file"
class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="FileNamePattern" value="logs/MyLog-%d{yyyy-MM-dd-HH-mm}.log.gz" />
<!-- The below param will keep the live update file in a different location-->
<!-- param name="ActiveFileName" value="current/MyLog.log" /-->
</rollingPolicy>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%5p %d{ISO8601} [%t][%x] %c - %m%n" />
</layout>
</appender>
Update: at least as early as 2013 (see Mubashar's comment) this started working.
According to Log4jXmlFormat you cannot configure it with log4j.properties, but only using the XML config format:
Note that TimeBasedRollingPolicy can only be configured with xml, not log4j.properties
Unfortunately, the example log4j.xml they provide doesn't work either:
log4j:ERROR Parsing error on line 14 and column 76
log4j:ERROR Element type "rollingPolicy" must be declared.
...
log4j:WARN Please set a rolling policy for the RollingFileAppender named 'FILE'
Toolbear74 is right log4j.XML is required.
In order to get the XML to validate the <param> tags need to be BEFORE the <rollingPolicy>
I suggest setting a logging threshold <param name="threshold" value="info"/>
When Creating a Log4j.xml file don't forget to to copy the log4j.dtd into the same location.
Here is an example:
<?xml version="1.0" encoding="windows-1252"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<!-- Daily Rolling File Appender that compresses old files -->
<appender name="file" class="org.apache.log4j.rolling.RollingFileAppender" >
<param name="threshold" value="info"/>
<rollingPolicy name="file"
class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="FileNamePattern"
value="${catalina.base}/logs/myapp.log.%d{yyyy-MM-dd}.gz"/>
<param name="ActiveFileName" value="${catalina.base}/logs/myapp.log"/>
</rollingPolicy>
<layout class="org.apache.log4j.EnhancedPatternLayout" >
<param name="ConversionPattern"
value="%d{ISO8601} %-5p - %-26.26c{1} - %m%n" />
</layout>
</appender>
<root>
<priority value="debug"></priority>
<appender-ref ref="file" />
</root>
</log4j:configuration>
Considering that your setting a FileNamePattern and an ActiveFileName I think that setting a File property is redundant and possibly even erroneous
Try renaming your log4j.properties and dropping in a log4j.xml similar to my example and see what happens.
Regarding error: log4j:ERROR Element type "rollingPolicy" must be declared
Use a log4j.jar version newer than log4j-1.2.14.jar, which has a log4j.dtd defining rollingPolicy.
of course you also need apache-log4j-extras-1.1.jar
Check if any other third party jars you are using perhaps have an older version of log4j.jar packed inside.
If so, make sure your log4j.jar comes first in the order before the third party containing the older log4j.jar.
In Log4j2, the "extras" lib is not mandatory any more. Also the configuration format has changed.
An example is provided in the Apache documentation
property.filename = /foo/bar/test.log
appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.fileName = ${filename}
appender.rolling.filePattern = /foo/bar/rolling/test1-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d %p %C{1.} [%t] %m%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 2
appender.rolling.policies.time.modulate = true
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=100MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 5
logger.rolling.name = com.example.my.class
logger.rolling.level = debug
logger.rolling.additivity = false
logger.rolling.appenderRef.rolling.ref = RollingFile
I'm suspicious of the ActiveFileName property. According to the log4j javadoc, there isn't such a property on the TimeBasedRollingPolicy class. (No setActiveFileName or getActiveFileName methods.)
I don't know what specifying an unknown property would do, but it is possible that it will cause the containing object to be abandoned, and that could lead to the warnings that you saw.
Try leaving it out and seeing what happens.
You have a bad package name
org.apache.log4j.rolling.RollingFileAppender
The correct one is:
org.apache.log4j.RollingFileAppender

Categories

Resources