Log4j: How to set up the simplest possible file logging?

My story:

I want to do what is as simple as the simplest log4j logger that writes lines to a file. I found several examples with some functionality, but not a basic, general one that really works, and not one with an explanation of how each line works.

Question:

Can anyone provide one?

The necessary conditions:

  • I already know where to put the file, and I have log4j configured and running on console logging.
  • Now I want to enter the file and also find the file from the file system after starting the program.
  • The lines to be added to the existing log4j.properties file are the desired result.
+49
java logging log4j
Jun 15 2018-11-15T00:
source share
4 answers

I have one common log4j.xml file for you:

 <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" > <log4j:configuration debug="false"> <appender name="default.console" class="org.apache.log4j.ConsoleAppender"> <param name="target" value="System.out" /> <param name="threshold" value="debug" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" /> </layout> </appender> <appender name="default.file" class="org.apache.log4j.FileAppender"> <param name="file" value="/log/mylogfile.log" /> <param name="append" value="false" /> <param name="threshold" value="debug" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" /> </layout> </appender> <appender name="another.file" class="org.apache.log4j.FileAppender"> <param name="file" value="/log/anotherlogfile.log" /> <param name="append" value="false" /> <param name="threshold" value="debug" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" /> </layout> </appender> <logger name="com.yourcompany.SomeClass" additivity="false"> <level value="debug" /> <appender-ref ref="another.file" /> </logger> <root> <priority value="info" /> <appender-ref ref="default.console" /> <appender-ref ref="default.file" /> </root> </log4j:configuration> 

with one console, two file applications and one registrar for the second file addition instead of the first.

EDIT

In one of the old projects, I found a simple log4j.properties file:

 # For the general syntax of property based configuration files see # the documentation of org.apache.log4j.PropertyConfigurator. # The root category uses two appenders: default.out and default.file. # The first one gathers all log output, the latter only starting with # the priority INFO. # The root priority is DEBUG, so that all classes can be logged unless # defined otherwise in more specific properties. log4j.rootLogger=DEBUG, default.out, default.file # System.out.println appender for all classes log4j.appender.default.out=org.apache.log4j.ConsoleAppender log4j.appender.default.out.threshold=DEBUG log4j.appender.default.out.layout=org.apache.log4j.PatternLayout log4j.appender.default.out.layout.ConversionPattern=%-5p %c: %m%n log4j.appender.default.file=org.apache.log4j.FileAppender log4j.appender.default.file.append=true log4j.appender.default.file.file=/log/mylogfile.log log4j.appender.default.file.threshold=INFO log4j.appender.default.file.layout=org.apache.log4j.PatternLayout log4j.appender.default.file.layout.ConversionPattern=%-5p %c: %m%n 

See the description of all layout arguments here: log4j PatternLayout Arguments

+65
Jun 15 2018-11-11T00:
source share
 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false"> <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender"> <param name="Threshold" value="INFO" /> <param name="File" value="sample.log"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d %-5p [%c{1}] %m %n" /> </layout> </appender> <root> <priority value ="debug" /> <appender-ref ref="fileAppender" /> </root> </log4j:configuration> 

Log4j can be a little confusing. So let's try to understand what is going on in this file: In log4j, you have two basic constructors: appenders and loggers.

Appenders determine how and where things are added. Will it be registered in the file, on the console, in the database, etc.? In this case, you indicate that the log instructions sent to the Appender file will be placed in the sample.log file using the template specified in the layout tags. You can also easily create an application for the console or database. Where the console appender will indicate things like the layout on the screen, and the database application will have connection information and table names.

Logs respond to logging events when they bubble. If the event arouses the interest of a particular registrar, he will refer to his attached applications. In the example below, you have only one root registrar, which by default responds to all registration events. In addition to the root log, you can specify more specific logs that respond to events from specific packages. These registrars may have their own applications specified using appender-ref tags, or else they inherit the set-top boxes from the root registrar. Using more specific registrars allows you to fine-tune the level of logging on specific packages or send specific packages to other applications.

So this file says:

  • Create an appender file that registers in the sample.log file
  • Attach this application to the root logger.
  • The root logger will respond to any event at least debug level
  • The application is configured only for log events that are at least as detailed as "information"

The cleanliness is that if you have logger.debug("blah blah") in your code, it will be ignored. A logger.info("Blah blah"); will be displayed in sample.log.

The snippet below can be added to the file above with the log4j tags. This registrar would inherit the domains from <root> , but would restrict all registration events from the org.springframework package org.springframework those who registered at info or higher.

  <!-- Example Package level Logger --> <logger name="org.springframework"> <level value="info"/> </logger> 
+28
Jun 15 2018-11-11T00:
source share

Here is a simple one that I often use:

 # Set up logging to include a file record of the output # Note: the file is always created, even if there is # no actual output. log4j.rootLogger=error, stdout, R # Log format to standard out log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern= %5p\t[%d] [%t] (%F:%L)\n \t%m%n\n # File based log output log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=owls_conditions.log log4j.appender.R.MaxFileSize=10000KB # Keep one backup file log4j.appender.R.MaxBackupIndex=1 log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern= %5p\t[%d] [%t] (%F:%L)\n \t%m%n\n 

The log format is as follows:

 ERROR [2009-09-13 09:56:01,760] [main] (RDFDefaultErrorHandler.java:44) http://www.xfront.com/owl/ontologies/camera/#(line 1 column 1): Content is not allowed in prolog. 

This format is determined by the line %5p\t[%d] [%t] (%F:%L)\n \t%m%n\n . You can read the meaning of the conversion characters in log4j javadoc for PatternLayout .

The comments included should help to understand what he is doing. Further notes:

  • it registers both the console and the file; in this case, the file is called owls_conditions.log : modify it according to your needs;
  • files rotate when they reach 10,000 KB and one backup file is saved
+8
Jun 15 2018-11-11T00:
source share

Here is the log4j.properties file that I have used with great success.

 logDir=/var/log/myapp log4j.rootLogger=INFO, stdout #log4j.rootLogger=DEBUG, stdout log4j.appender.stdout=org.apache.log4j.DailyRollingFileAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{MM/dd/yyyy hh:mm:ss a}|%-5p|%-30c{1}| %m%n log4j.appender.stdout.DatePattern='.'yyyy-MM-dd log4j.appender.stdout.File=${logDir}/myapp.log log4j.appender.stdout.append=true 

DailyRollingFileAppender will create new files every day with file names that look like this:

 myapp.log.2017-01-27 myapp.log.2017-01-28 myapp.log.2017-01-29 myapp.log <-- today log 

Each entry in the log file will have the following format:

 01/30/2017 12:59:47 AM|INFO |Component1 | calling foobar(): userId=123, returning totalSent=1 01/30/2017 12:59:47 AM|INFO |Component2 | count=1 > 0, calling fooBar() 

Set the location of the above file using -Dlog4j.configuration , as indicated in this publication :

 java -Dlog4j.configuration=file:/home/myapp/config/log4j.properties com.foobar.myapp 

In your Java code, you must specify the name of each software component when creating an instance of the registration object. I would also like to go into the log file and standard output, so I wrote this little function.

 private static final Logger LOGGER = Logger.getLogger("Component1"); public static void log(org.apache.log4j.Logger logger, String message) { logger.info(message); System.out.printf("%s\n", message); } public static String stackTraceToString(Exception ex) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); return sw.toString(); } 

And then call it like this:

 LOGGER.info(String.format("Exception occurred: %s", stackTraceToString(ex))); 
0
Jan 30 '17 at 22:04
source share



All Articles