Log4j configuration with log4j.xml
Logging to console:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration debug="true" 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="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" /> </layout> </appender> <root> <level value="DEBUG" /> <appender-ref ref="console" /> </root> </log4j:configuration>
Here logging level is set at DEBUG, Appender is console,Layout is Pattern with timestamp.
Logging to file:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration debug="true" xmlns:log4j='http://jakarta.apache.org/log4j/'> <appender name="file" class="org.apache.log4j.RollingFileAppender"> <param name="append" value="false" /> <param name="maxFileSize" value="10MB" /> <param name="maxBackupIndex" value="10" /> <param name="file" value="D:/AppLog/applog.log" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" /> </layout> </appender> <root> <level value="ERROR" /> <appender-ref ref="file" /> </root> </log4j:configuration>
Here logging level is set at ERROR, Appender is file, Layout is Pattern with timestamp.
Logging to DB:
Suppose we have table in our DB:
CREATE TABLE LOG_TABLE (USER_ID VARCHAR(10) NOT NULL, DATED DATE NOT NULL, LOGGER VARCHAR(50) NOT NULL, LEVEL VARCHAR(10) NOT NULL, MESSAGE VARCHAR(1000) NOT NULL );
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration debug="true" xmlns:log4j='http://jakarta.apache.org/log4j/'> <appender name="DB" class="org.apache.log4j.jdbc.JDBCAppender"> <param name="url" value="jdbc:mysql://localhost/DBNAME"/> <param name="driver" value="com.mysql.jdbc.Driver"/> <param name="user" value="username"/> <param name="password" value="password"/> <param name="sql" value="INSERT INTO LOG_TABLE VALUES('%x', '%d','%C','%p','%m')"/> <layout class="org.apache.log4j.PatternLayout"> </layout> </appender> <root> <level value="ERROR" /> <appender-ref ref="DB" /> </root> </log4j:configuration>
Here logging level is set at ERROR, Appender is DB, Layout is Pattern with timestamp.