java日志代码 java的日志

java怎么写日志记录,最好是完整的代码!谢啦!常用2种方式 , 具体你可以去自己写,建议,编程前期主要靠你自己琢磨 , 他人给你思路即可 。
1.用简单的读写文件实现,写一个写文件的共用类,每次把日志写到文件里即可 。
2.用开源免费的日志工具,如log4j 。
祝你成功?。?
JAVA 采用单例设计模式设计日志处理类,并写出代码import java.util.Date;
public class Logger {
private static Logger instance;
private static Class clazz;
private Logger() {
}
private Logger(Class clazz) {
this.instance = new Logger();
this.clazz = clazz;
}
public static Logger getLogger(Class clazz) {
if (instance == null) {
【java日志代码 java的日志】synchronized (Logger.class) {
if (instance == null) {
instance = new Logger(clazz);
}
}
}
return instance;
}
public void info(String msg) {
System.out.println(clazz.getName() + "[" + new Date().toLocaleString()
+ "][info]:" + msg);
}
public void error(String msg) {
System.out.println(clazz.getName() + "[" + new Date().toLocaleString()
+ "][error]:" + msg);
}
public void warn(String msg) {
System.out.println(clazz.getName() + "[" + new Date().toLocaleString()
+ "][warn]:" + msg);
}
public void log(String msg) {
System.out.println(clazz.getName() + "[" + new Date().toLocaleString()
+ "][log]:" + msg);
}
public static void main(String args[]) {
Logger s = Logger.getLogger(String.class);
s.info("普通消息");
}
}
java怎么运用切面编程生成日志1.首先创建一个自定义注解拦截Controller类,代码如下
/**
* 自定义注解 拦截Controller
*/
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ControllerLog {
String desc() default "";//标示默认打印空
}
2.创建一个打印日志的切面类 , 引入切面注解@Aspect , 
新建方法代码如下:
// Controller层切点
@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
public void recordLog() {
}
@Around("recordLog()")
public Objectaround(ProceedingJoinPoint pjp) throws Throwable {
//ExPatternParser.initLogger();
long start = System.currentTimeMillis();
Object[] args = pjp.getArgs();
String remark = this.getControllerMethodDescription(pjp);
Object retVal = null;
try {
retVal = pjp.proceed();
} catch (Throwable e) {
// TODO Auto-generated catch block
logger.error("请求失败" + e.toString(),e);
remark = remark+ " 。Exception Cause By " + e.toString();
throw e;
}finally{
long end = System.currentTimeMillis();
long cost = end - start;
//打印访问日志
// Controller中所有方法的参数,前两个分别为:Request,Response
if(args != nullargs.length0){
Object o = args[0];
if(o instanceof HttpServletRequest){
HttpServletRequest request = (HttpServletRequest) args[0];
PrintLog.visit(request, cost,remark);
}
}
}
return retVal;
}
/**
* 获取注解中对方法的描述信息 用于Controller层注解
* @param joinPoint切点
* @return 方法描述
* @throws Exception
*/
public static String getControllerMethodDescription(ProceedingJoinPoint joinPoint)
throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);

推荐阅读