环境:spring boot +maven
- maven引用
<!--log4j日志--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
- src目录中创建log4j.properties
### 设置### 设置记录日志方式 下面配置每个记录方式的详细 log4j.rootLogger=INFO,stdout,database ### 输出信息到控制台### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n #调试打开 log4j.logger.com.hibernate=DEBUG log4j.logger.com.hibernate.common.jdbc.SimpleDataSource=DEBUG log4j.logger.com.hibernate.common.jdbc.ScriptRunner=DEBUG log4j.logger.com.hibernate.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG # 日志输出到数据库 # Define the root logger with appender file log4j.appender.database=org.apache.log4j.jdbc.JDBCAppender #log4j.appender.database.Encoding=UTF-8 #定义字符集防止中文乱码 log4j.appender.database.Threshold=WARN #log4j.appender.dblog.BufferSize=10 #日志缓存;这个配置可以提交性能;累计操作N(10)个记录一次性写入数据库 log4j.appender.database.driver=org.postgresql.Driver log4j.appender.database.URL=jdbc:postgresql://localhost:5432/singlewood log4j.appender.database.user=singlewood log4j.appender.database.password=singlewood log4j.appender.database.sql=INSERT INTO sys_log(content, create_time,leve) VALUES ('%m', to_timestamp('%d{yyyy-MM-dd HH:mm:ss}', 'YYYY-MM-DD HH24:MI:SS'),'%X{leve}') log4j.appender.database.layout=org.apache.log4j.PatternLayout log4j.appender.database.layout.ConversionPattern=-[%d{yyyy-MM-dd HHmmss}]-[%C{1}]-[%M]-%X{clientIp}-%X{operateModuleName}-%X{username}-%X{operateContent}-%X{operateResult}-%m-%n
- 使用
public class UserServiceImpl implements UserService { @Autowired private UserDao dao; private Logger logger = Logger.getLogger(UserServiceImpl.class); @Override public boolean Login(String loginName, String passWord) { BsUser user= dao.findloginName(loginName); if(user.getULoginName()==loginName){ try{ return PasswordEncryptionUtil.getEncryptedPassword(passWord,user.getUSalt()).equals(user.getUPassWord()); } catch(Exception e){ MDC.put("leve", "error"); #自定义参数方法第一个参数为参数名 logger.error("验证密码时出错:"+e.getMessage());
MDC.remove("leve"); return false; } } return false; } }