How to use java.util.logger in a web application?

被刻印的时光 ゝ 提交于 2019-12-05 16:04:25

I'd consider using a logging framework such as Log4J.

Using it would just boil down to configuring the appenders (e.g. FileAppender) and log levels in a central file (.xml or .properties) and in each class that needs to define a logger you'd just do Log l = LogFactory.getLog(clazz); (where clazz is the class you define the logger for).

You could make the logger public static and use it from other classes as well but I'd not recommend it, since you normally want to know which logger (i.e. which class that logger was defined for) generated a log entry.

You could use the logging.properties file to define your handlers globally for the whole application. In this file you can fine-tune your logging needs.

Look here or just google for logging.properties.

Example from the link above:

handlers = java.util.logging.ConsoleHandler, java.util.logging.FileHandler

java.util.logging.ConsoleHandler.level = INFO
java.util.logging.FileHandler.level = ALL

java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

You can even setup different logging behavior for each of you web applications by placing the logging.properties in WEB-INF/classes of your web app.

Saideswara Rao.Bojja
package package_name;

import java.io.IOException;

import java.util.Properties;

import org.apache.log4j.Logger;

import org.apache.log4j.PropertyConfigurator;


public class Log {

public  Log() 
{
        Properties props = new Properties();
    try {
        props.load(getClass().getResourceAsStream("/log4j.properties"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    PropertyConfigurator.configure(props);//PropertyConfigurator.configure("log4j.properties");
}

public  Logger getLogger(Object obj) 
{
    Logger logger = Logger.getLogger(Object.class);
    return logger;
}

}

then we have to maintain a log4j.properties file in one of our packages,and the file should be as follows,

log4j.properties

log4j.rootLogger=DEBUG, R,CA

log4j.appender.R = org.apache.log4j.DailyRollingFileAppender

log4j.appender.R.File = c:\\our project name+LOGSLIVE\\logs\\project short name.log

log4j.appender.R.Append = true

log4j.appender.R.DatePattern = '_'yyyy-MM-dd'.log'

log4j.appender.R.layout = org.apache.log4j.PatternLayout

#log4j.appender.R.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [%t] [%p] %m%n

log4j.appender.R.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %5p [%t] (%F:%L) -  %m%n


#Console Appender

log4j.appender.CA=org.apache.log4j.ConsoleAppender

log4j.appender.CA.layout=org.apache.log4j.PatternLayout

log4j.appender.CA.layout.ConversionPattern=%5p [%t] (%F:%L) -  %m%n
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!