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)));
stackoverflowuser2010 Jan 30 '17 at 22:04 2017-01-30 22:04
source share