Multiple log files using log4j appender
Log4j is no doubt is "the best" library for logging purpose and it is used by a lot of developers. It provides many appenders ranging from plain text files to HTML appenders to SMTP appender etc... and also, it allows us to write our own appender.
In this post I'll discuss how you can create a dedicated appender which can be used to generate the separate/second log file independent of root logger.
1) First thing you need to do is, define a custom logger configuration which we'll be using later (promise, I'll show how?). Below is the sample configuration:
(this should go to your log4j.properties file)
log4j.logger.myLogger=DEBUG, mylogger
log4j.appender.mylogger=org.apache.log4j.RollingFileAppender
log4j.appender.mylogger.maxFileSize=5000KB
log4j.appender.mylogger.layout=org.apache.log4j.PatternLayout
log4j.appender.mylogger.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %c : %m%n
log4j.appender.mylogger.File=c:/seconf_file.log
Note the first line, we have given a name (myLogger) to our logger and we'll be using this name in our code to get instance of our custom logger (mylogger).
2) Second, to use this appender you have to get an instance of it. Below is the sample code which shows how to do it (I completed my promise):
private or public (whatever you want)
private static final Logger log = Logger.getLogger("myLogger");
with the "log" instance you can send your log statemnts to a selected logger (in this case mylogger, which will go to seconf_file.log)
Similarly you can define your own loggers and use them as and when needed.
Enjoy !!!!!
In this post I'll discuss how you can create a dedicated appender which can be used to generate the separate/second log file independent of root logger.
1) First thing you need to do is, define a custom logger configuration which we'll be using later (promise, I'll show how?). Below is the sample configuration:
(this should go to your log4j.properties file)
log4j.logger.myLogger=DEBUG, mylogger
log4j.appender.mylogger=org.apache.log4j.RollingFileAppender
log4j.appender.mylogger.maxFileSize=5000KB
log4j.appender.mylogger.layout=org.apache.log4j.PatternLayout
log4j.appender.mylogger.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %c : %m%n
log4j.appender.mylogger.File=c:/seconf_file.log
Note the first line, we have given a name (myLogger) to our logger and we'll be using this name in our code to get instance of our custom logger (mylogger).
2) Second, to use this appender you have to get an instance of it. Below is the sample code which shows how to do it (I completed my promise):
private or public (whatever you want)
private static final Logger log = Logger.getLogger("myLogger");
with the "log" instance you can send your log statemnts to a selected logger (in this case mylogger, which will go to seconf_file.log)
Similarly you can define your own loggers and use them as and when needed.
Enjoy !!!!!
Comments
Thanks,
Miguel Garz