`

自己写个java日志类及使用

 
阅读更多
package xxx.common.framework.util;

import java.io.File;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public abstract class GenericLogger
  implements LoggerInterface
{
  public static final int APP_DEBUG = 9;
  public static final int DEBUG = 8;
  public static final int REQUEST = 7;
  public static final int CLIENT = 6;
  public static final int EVENT = 5;
  public static final int STAT = 4;
  public static final int INFO = 3;
  public static final int CONTROL = 2;
  public static final int ERROR = 1;
  public static final int ALERT = 0;
  protected static final int FILE_MODE = 0;
  protected static final int STDOUT_MODE = 1;
  protected static final int BOTH_MODE = 2;
  protected PrintWriter writer = null;
  protected int mode = 1;
  protected int logLevel = 9;
  protected String logFilePath = ".";
  protected String logFileName = "logger.log";

  protected GenericLogger()
  {
    init();

    if (this.logLevel == 8)
      this.logLevel = redefineDebug();
  }

  protected void init()
  {
  }

  protected int redefineDebug()
  {
    return 8;
  }

  public void logAppDebug(Object msg) {
    logAppDebug(null, msg);
  }

  public void logAppDebug(Object caller, Object msg) {
    logAction(9, "APP.. ", caller, msg);
  }

  public void logDebug(Object msg) {
    logDebug(null, msg);
  }

  public void logDebug(Object caller, Object msg) {
    logAction(8, "DEBUG ", caller, msg);
  }

  public void logRequest(Object msg) {
    logRequest(null, msg);
  }

  public void logRequest(Object caller, Object msg) {
    logAction(7, "REQ.. ", caller, msg);
  }

  public void logClient(Object msg) {
    logClient(null, msg);
  }

  public void logClient(Object caller, Object msg) {
    logAction(6, "CLNT. ", caller, msg);
  }

  public void logEvent(Object msg) {
    logEvent(null, msg);
  }

  public void logEvent(Object caller, Object msg) {
    logAction(5, "EVENT ", caller, msg);
  }

  public void logStat(Object msg) {
    logStat(null, msg);
  }

  public void logStat(Object caller, Object msg) {
    logAction(4, "STAT. ", caller, msg);
  }

  public void logInfo(Object msg) {
    logInfo(null, msg);
  }

  public void logInfo(Object caller, Object msg) {
    logAction(3, "INFO. ", caller, msg);
  }

  public void logControl(Object msg) {
    logControl(null, msg);
  }

  public void logControl(Object caller, Object msg) {
    logAction(2, "CTRL. ", caller, msg);
  }

  public void logError(Object msg) {
    logError(null, msg);
  }

  public void logError(Object caller, Object msg) {
    logAction(1, "ERROR ", caller, msg);
  }

  public void logAlert(Object msg) {
    logAlert(null, msg);
  }

  public void logAlert(Object caller, Object msg) {
    logAction(0, "ALERT ", caller, msg);
  }

  protected synchronized void logAction(int level, String prefix, Object caller, Object msg) {
    try {
      if (shouldLog(level)) {
        String message = formatMessage(prefix, formatClassName(caller) + msg);
        if ((this.mode == 0) || (this.mode == 2)) {
          this.writer.println(message);
          this.writer.flush();
        }

        if ((this.mode == 1) || (this.mode == 2))
          System.out.println(message);
      }
    }
    catch (Exception e) {
      System.out.println(getClass().toString() + " exception: " + e);
      e.printStackTrace();
    }
  }

  public static String formatClassName(Object caller)
  {
    String name = "";
    if (caller != null) {
      name = caller.getClass().getName();
      name = name.substring(name.lastIndexOf(".") + 1, name.length());
      name = "[" + name + "] ";
    }
    return name;
  }

  public static String formatMessage(String prefix, String msg) {
    String pattern = "dd-MM-yyyy HH:mm:ss:SSS";
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    Date current = new Date();
    String dateString = "[" + sdf.format(current) + "]";
    return prefix + dateString + " " + msg;
  }

  public static String constructFullPath(String path, String file) {
    if ((path == null) || (path.trim().equals(""))) {
      return file;
    }

    int index = path.lastIndexOf(File.separator);
    if ((index < 0) || (index != path.length() - File.separator.length())) {
      return path + File.separator + file;
    }

    return path + file;
  }

  protected boolean isValidLogLevel(int level) {
    switch (level) { case 9:
      break;
    case 8:
      break;
    case 7:
      break;
    case 6:
      break;
    case 5:
      break;
    case 4:
      break;
    case 3:
      break;
    case 2:
      break;
    case 1:
      break;
    case 0:
      break;
    default:
      String str = getClass().toString() + ": unknown log level";
      System.out.println(str);
      return false;
    }
    return true;
  }

  protected boolean shouldLog(int level) {
    if (!isValidLogLevel(level)) {
      return false;
    }

    if (level == 8) {
      return redefineDebug() <= this.logLevel;
    }

    return level <= this.logLevel;
  }

  public int getLogLevel() {
    return this.logLevel;
  }

  public void recording(ServletRequest request)
  {
    if (getLogLevel() < 7) return;

    StringBuffer buffer = new StringBuffer();
    String valueAction = request.getParameter("action");
    if (valueAction != null) {
      buffer.append("(" + valueAction + ")");
    }
    Enumeration e = request.getParameterNames();
    while (e.hasMoreElements()) {
      String parameterName = (String)e.nextElement();
      if (!parameterName.equals("action"))
      {
        String[] values = (String[])request.getParameterValues(parameterName);
        for (int i = 0; i < values.length; i++) {
          String valueString = values[i];
          if (valueString == null) valueString = "null";
          buffer.append(" " + parameterName + "=(" + valueString + ")");
        }
      }
    }
    HttpSession session = ((HttpServletRequest)request).getSession(false);
    String id = session == null ? "unknown" : session.getId();
    logRequest(GenericLoggerTag.handleAction(id) + buffer);
  }

  public void measuringClientTime(ServletRequest request) {
    if (!enableClientTimeMeasurement()) return;

    String clientBeginTime = request.getParameter("client_begin_time");
    String clientEndTime = request.getParameter("client_end_time");
    HttpSession session = ((HttpServletRequest)request).getSession(false);
    String id = session == null ? "unknown" : session.getId();
    if ((clientEndTime != null) && (!clientEndTime.equals(""))) {
      logClient(">> CLNT. [" + clientEndTime.replace('|', ' ') + "] " + GenericLoggerTag.endClient(id) + request.getParameter("pre_action"));
    }

    if ((clientBeginTime != null) && (!clientBeginTime.equals("")))
      logClient(">> CLNT. [" + clientBeginTime.replace('|', ' ') + "] " + GenericLoggerTag.beginClient(id) + request.getParameter("action"));
  }

  public boolean enableClientTimeMeasurement()
  {
    return (getLogLevel() >= 6) && (getLogLevel() != 7);
  }

  public boolean enableClientPositionMeasurement()
  {
    return getLogLevel() >= 7;
  }
}
_____________________________________
package xxx.common.framework.util;

public class GenericLoggerTag
{
  public static final String BEGIN_CLIENT = " begin.client=";
  public static final String BEGIN_TESTCASE = " begin.testcase=";
  public static final String ABORT_TESTCASE = " abort.testcase=";
  public static final String BEGIN_ACTION = " begin.action=";
  public static final String HANDLE_ACTION = " handle.action=";
  public static final String DETAIL_ACTION = " detail.action=";
  public static final String DETAIL_IDENTITY = " detail.identity=";
  public static final String HANDLE_EVENT = "  handle.event=";
  public static final String BEGIN_WEB = "  begin.web=";
  public static final String BEGIN_EJB = "   begin.ejb=";
  public static final String DETAIL_EJB = "   detail.ejb=";
  public static final String BEGIN_SQL = "    begin.sql=";
  public static final String END_SQL = "    end...sql=";
  public static final String BEGIN_RS = "    begin.rs=";
  public static final String END_RS = "    end...rs=";
  public static final String BEGIN_CONNECT = "    begin.connect=";
  public static final String END_CONNECT = "    end...connect=";
  public static final String BEGIN_EAI = "    begin.eai=";
  public static final String END_EAI = "    end...eai=";
  public static final String END_EJB = "   end...ejb=";
  public static final String END_WEB = "  end...web=";
  public static final String END_ACTION = " end...action=";
  public static final String END_TESTCASE = " end...testcase=";
  public static final String END_CLIENT = " end...client=";
  public static final String BEGIN_TASK = " begin.task=";
  public static final String END_TASK = " end...task=";
  public static final String REDIRECT_CLIENT = ">> CLNT. ";

  public static String format(String id)
  {
    return "[ID=" + id + "]";
  }

  public static String beginAction(String id) {
    return format(id) + " begin.action=";
  }

  public static String endAction(String id) {
    return format(id) + " end...action=";
  }

  public static String beginWeb(String id) {
    return format(id) + "  begin.web=";
  }

  public static String endWeb(String id) {
    return format(id) + "  end...web=";
  }

  public static String beginEjb(String id) {
    return format(id) + "   begin.ejb=";
  }

  public static String endEjb(String id) {
    return format(id) + "   end...ejb=";
  }

  public static String beginTask(String id) {
    return format(id) + " begin.task=";
  }

  public static String endTask(String id) {
    return format(id) + " end...task=";
  }

  public static String beginClient(String id) {
    return format(id) + " begin.client=";
  }

  public static String endClient(String id) {
    return format(id) + " end...client=";
  }

  public static String handleEvent(String id) {
    return format(id) + "  handle.event=";
  }

  public static String handleAction(String id) {
    return format(id) + " handle.action=";
  }

  public static String beginSql(String id) {
    return format(id) + "    begin.sql=";
  }

  public static String endSql(String id) {
    return format(id) + "    end...sql=";
  }

  public static String beginRs(String id) {
    return format(id) + "    begin.rs=";
  }

  public static String endRs(String id) {
    return format(id) + "    end...rs=";
  }

  public static String beginConnect(String id) {
    return format(id) + "    begin.connect=";
  }

  public static String endConnect(String id) {
    return format(id) + "    end...connect=";
  }

  public static String beginEai(String id) {
    return format(id) + "    begin.eai=";
  }

  public static String endEai(String id) {
    return format(id) + "    end...eai=";
  }

  public static String beginTestcase(String id) {
    return format(id) + " begin.testcase=";
  }

  public static String endTestcase(String id) {
    return format(id) + " end...testcase=";
  }

  public static String abortTestcase(String id) {
    return format(id) + " abort.testcase=";
  }
}
___yyy.properties___________________________________

#---------------------
# Logger
#---------------------
Logger.mode=2
Logger.level=9
Logger.file.path=D:\\CD\\tomcat_yyy\\webapps\\ATS\\WEB-INF\\classes\\logs
Logger.file.name=yyy_server.log
Logger.debug.redefine=


___AtsLogger.java______________

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.xxx.mil.application.yyy.util;

/**
 *
 */

import java.io.*;
import xxx.common.framework.util.*;

public class AtsLogger extends GenericLogger {

    protected static final String MODE_KEY  = "Logger.mode";
    protected static final String LEVEL_KEY = "Logger.level";
    protected static final String PATH_KEY  = "Logger.file.path";
    protected static final String NAME_KEY  = "Logger.file.name";
    protected static final String DEBUG_KEY = "Logger.debug.redefine";

    // All variables should be static to avoid being re-initalized after super()
    private static int redefined = DEBUG;

    // Singleton
    private static AtsLogger out;

    public static AtsLogger getInstance() {
        if (out == null) out = new AtsLogger();
        return out;
    }

    protected void init() {
        try {
            GenericResourceReader manager = AtsResourceReader.in;
            mode = manager.getInt(MODE_KEY);
            logLevel = manager.getInt(LEVEL_KEY);
            logFilePath = manager.getSafeString(PATH_KEY);
            logFileName = manager.getSafeString(NAME_KEY);
            if (mode == FILE_MODE || mode == BOTH_MODE) {
                String file = constructFullPath(logFilePath, logFileName);
                FileWriter fw = new FileWriter(file, true);
                writer = new PrintWriter(fw);
            }

            System.out.println("[" + getClass().toString() + "] mode=" + mode + " level=" + logLevel);

        } catch (Exception e) {
            mode = STDOUT_MODE;
            logLevel = APP_DEBUG;
            System.out.println(getClass().toString() + " init(): exception: " + e);
            System.out.println(getClass().toString() + " init(): log mode is set to STDOUT");
            System.out.println(getClass().toString() + " init(): log level is set to APP_DEBUG");
        }
        try {
            GenericResourceReader manager = AtsResourceReader.in;
            redefined = manager.getInt(DEBUG_KEY);
        } catch (Exception e) {
            redefined = DEBUG;
        }
    }
    protected int redefineDebug() {
        return redefined;
    }
}

_______Usage__________________________________

public class C1{
    private AtsLogger logger = AtsLogger.getInstance();
    private AtsLoggerTag loggerTag = AtsLoggerTag.getInstance();
		
		public CourseSession getCpdtsCourse(String courseCode, String sessionCode) throws Exception {
        CourseSession searchCourseSession = new CourseSession();

//        Logger.writeLogln("CpdtsManager.getCpdtsCourse {");
        String key = courseCode + "@@" + sessionCode;
        String logAction = "GetCpdtsCourse.";
        logger.logRequest(loggerTag.beginAction(key)+ logAction);
        searchCourseSession = getDao().searchCourseSession(courseCode, sessionCode);
        logger.logRequest(loggerTag.endAction(key)+ logAction);
//        Logger.writeLogln("}  //getCpdtsCourse");

       return searchCourseSession;
    }

}

 

分享到:
评论

相关推荐

    java日志工具类 java日志工具类

    java日志工具类 java日志工具类java日志工具类 java日志工具类java日志工具类 java日志工具类java日志工具类 java日志工具类java日志工具类 java日志工具类java日志工具类 java日志工具类java日志工具类 java日志...

    java日志处理类

    java日志处理类

    一个Java写的日志分析工具

    总的来说,这个Java日志分析工具提供了对日志数据进行处理和分析的功能,通过阅读源代码,开发者可以学习到Java日志处理的最佳实践,以及如何构建此类工具。同时,对于需要排查问题或监控系统运行状态的用户,这个...

    java写日志文件

    java 写日志记录到指定目录下(一天一个文档)

    java日志文件过滤

    在Java编程领域,日志文件过滤是一个至关重要的实践,它主要涉及到如何管理和分析应用程序生成的日志...通过学习和理解这个项目,你可以深化对Java日志处理、文件I/O和条件过滤等技术的理解,并应用到自己的项目中。

    Java自定义日志工具类

    在给定的描述中,这个Java日志工具类不仅支持在控制台上实时显示日志信息,还具备将日志数据持久化到文件的能力。这样的设计有助于在不影响程序运行的情况下收集和保存日志,尤其是在生产环境中,当需要分析历史日志...

    JAVA版简单日志工具类

    总的来说,这个"JAVA版简单日志工具类"为小型Java项目提供了一种轻量级的日志解决方案,既满足了基本的日志记录需求,又保持了代码的简洁性和可扩展性。通过合理使用,可以在开发过程中极大地提高效率。

    日志工具类-java实现

    在Java编程中,日志工具类的实现是一个非常重要的部分,尤其在开发复杂项目时,良好的日志系统能够帮助开发者追踪程序运行状态、定位错误、分析性能等。本篇文章将详细探讨如何创建一个自定义的日志工具类,以便在...

    android--java写日志文件

    总之,正确地使用Java在Android中写日志是优化应用质量和提升开发效率的重要手段。理解不同日志级别,遵循良好的日志编写习惯,并根据需要扩展日志功能,将有助于在开发过程中快速定位和解决问题。

    java工具类,日志处理类

    总结来说,这个压缩包提供的内容涵盖了Java编程中的几个核心概念:工具类的实用方法、异常处理的统一策略以及灵活的日志系统。这些组件是构建健壮、可维护的Java应用的基础,对于任何Java开发者来说,理解和掌握这些...

    自己写的java日志类和方法代码分享

    尽管这个自定义的日志类满足了基本的日志记录需求,但在实际的大型项目中,通常会使用成熟的日志框架,如Log4j、SLF4J或Java内置的`java.util.logging.Logger`。这些框架提供了更高级的功能,如日志级别控制、日志...

    java 日志的数据脱敏的实现方法

    总的来说,Java日志数据脱敏是一个重要的安全实践,通过在Model层定义接口并创建对象副本,可以有效地平衡日志的可用性和安全性。这种实现方式允许我们在不破坏原始数据完整性的前提下,保护日志中的敏感信息。在...

    java Log日志规范

    Java日志规范是Java开发中不可或缺的一部分,它用于记录应用程序运行过程中的各种信息,包括错误、警告、调试信息等,帮助开发者追踪问题、优化性能。本文将深入探讨Java的日志规范,以log4j2.properties、log4j....

    Java自定义日志模块实现

    自定义日志模块(接口及代理实现),而不直接使用第三方日志框架接口,避免在日志框架升级或者切换时,代码过多耦合。 这个举例说明一下: 比如,在某一项目开始时使用的是“log4j”框架,后面经过研究发现“sf4j...

    自己写的简易版Java日志类分享

    这个简易版的Java日志类提供了一个基本的日志记录功能,适用于小型项目或者学习用途。下面将详细介绍这个日志类的主要特点、结构和使用方法。 1. **日志文件路径管理**: - `logFilePath` 是用来存储日志文件的...

    java语言编写的日历日志程序

    Java语言编写的日历日志程序是一个典型的课程设计项目,主要目标是让学生掌握Java编程基础以及实际应用。这个程序提供了日历浏览和日志管理的功能,对于初学者来说,这样的项目能够帮助他们深入理解面向对象编程、...

    使用Java正则表达式分析处理日志

    在提供的两个示例类中,可能会展示具体的日志处理代码,包括正则表达式的使用和处理逻辑。通过阅读这些示例,可以更深入地了解如何将上述理论应用于实际项目。 总的来说,Java正则表达式是处理日志的强大工具,它能...

    java发送syslog日志,支持多目的ip

    在提供的资源中,`SysLogTest.7z`是一个使用NetBeans开发的Java应用程序,它实现了上述的功能,可以直接运行。根目录下的bat文件是启动脚本,执行后可以测试该程序的Syslog发送能力。 另一方面,`Syslog Watcher....

    Java程序日志类jar包

    在给定的"Java程序日志类jar包"中,我们可以推测其中可能包含了诸如Log4j、SLF4J、Logback等主流的日志处理框架的库文件,这些框架在Java生态系统中广泛被使用。 1. **Log4j**: 是Apache的一个开源项目,它为应用...

    java日志记录工具类

    调用方法:IndexDataLog.print(入参),可以设置文件大小,文件写满以后自动创建新的日志文件。一般用来记录用户的搜索词,或操作记录。目前以json格式保存日志,入参稍作修改,可以传入对象,linux和windows都支持。

Global site tag (gtag.js) - Google Analytics