(1)PropertyConfigurator.configure("log4j.properties") 默认读取的是项目根目录的路径。此时的log4j.properties要放在项目目录下。
如图在项目目录下创建config文件夹(注意:不是在src文件下),此时,config和src是同级目录
(3)项目打成jar包时,一般不会把配置文件也打进jar包。
- PropertyConfigurator.configure("config/log4j.properties");
<!-- Spring刷新Log4j配置文件变动的间隔,单位为毫秒 -->
- <!-- 设置由Sprng载入的Log4j配置文件位置 -->
- <context-param>
- <param-name>log4jConfigLocation</param-name>
- <param-value>WEB-INF/classes/log4j.properties</param-value>
- </context-param>
2、可以通过资源类对资源文件进行加载,与使用为一体
- <context-param>
- <param-name>log4jRefreshInterval</param-name>
- <param-value>10000</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
- </listener>
- public class TestLog4j {
- public static void main(String[] args) {
- PropertyConfigurator.configure( " D:/Code/conf/log4j.properties " );
- Logger logger = Logger.getLogger(TestLog4j. class );
- logger.debug( " debug " );
- logger.error( " error " );
- }
- }
通过指定的名字获得记录器,如果必要的话,则为这个名字创建一个新的记录器。Name一般取本类的名字,比如:
- public static Logger getLogger( String name),
注:推荐使用commons-logging结合log4j进行日志记录
- static Logger logger = Logger.getLogger ( ServerWithLog4j.class.getName () ) ;
2.插入记录信息(格式化日志信息)
- private static Log logger = LogFactory.getLog(Yourclass.class);
例如:
- Logger.debug ( Object message ) ;
- Logger.info ( Object message ) ;
- Logger.warn ( Object message ) ;
- Logger.error ( Object message ) ;
- import org.apache.log4j.*;
- public class LogTest ...{
- static Logger logger = Logger.getLogger(LogTest.class.getName());
- public static void main(String[] args) ...{
- //通过PropertyConfigurator加载log4j.properties文件,如果不添加这句话,则有spring加载
- PropertyConfigurator.configure ( “.\srclog4j.properties”);
- logger.debug("Debug ...");
- logger.info("Info ...");
- logger.warn("Warn ...");
- logger.error("Error ...");
- }
- }