简体   繁体   English

Java自定义记录器:记录标准或/和最佳实践

[英]Java custom logger: logging standards or/and best practices

I am developing a framework and I want the jar to be light weight and independent as much as it can be. 我正在开发一个框架,我希望jar重量轻,尽可能独立。

So I wrote a logging class: 所以我写了一个日志类:

import java.util.Date;
import java.util.Properties;

public class Logger {

    private static final Logger me = new Logger();
    private static boolean info = false;
    private static boolean debug = false;
    private static boolean error = false;
    private static String className = null;

    public static Logger getInstance(Class<?> clazz) {  
        className = clazz.getCanonicalName();
        try {
            Properties props = new CustProps().load(clazz);
            if(props.get(CustProps.NAME_LOG_MODE) != null) {
                String devMode = props.getProperty(CustProps.NAME_LOG_MODE)
                                   .toLowerCase();
                if("info".equals(devMode)) {
                    info = true;
                    debug = true;
                } else if("debug".equals(devMode)) {
                    debug = true;
                } 
            }
        } catch (Exception e) {
            // debug is error by default
        }

        error = true;
        return me;
    }

    public void logError(Object msg) {
        if(isError()) {
            System.out.println(new Date().toString()
              + " ERROR ["+Logger.className+"] - " + msg);
        }
    }

    public void logDebug(Object msg) {
        if(isDebug()) {
            System.out.println(new Date().toString()
              + " DEBUG ["+Logger.className+"] - " + msg);
        }
    }

    public void logInfo(Object msg) {
        if(isInfo()) {
            System.out.println(new Date().toString()
              + " INFO ["+Logger.className+"] - " + msg);
        }
    }

    public boolean isInfo() { return Logger.info; }

    public boolean isDebug() { return Logger.debug; }

    public boolean isError() { return Logger.error; }

}
  • What are the best practices to make this logging better? 使这种日志记录变得更好的最佳做法是什么?
  • Is making your own logger even worth it? 让自己的记录器值得吗?
  • Will the use of this logger make my framework worse than choosing something existing (like log4j )? 使用这个记录器会使我的框架比选择现有的东西(比如log4j )更糟糕吗?

I would STRONGLY recommend that you use slf4j as your logging API, as it is designed to be able to switch backends at deployment time. 我强烈建议您使用slf4j作为日志API,因为它旨在能够在部署时切换后端。 In other words, if you ever outgrow your own logging framework or has to interface with others using something else, it is simple to change your mind. 换句话说,如果你曾经不再使用自己的日志框架,或者必须使用其他东西与其他人交互,那么改变主意很容易。

http://slf4j.org/ http://slf4j.org/

It also allows you to use the {}-construction for easy inserting objects in your log strings without overhead if that string is not actually logged anyway (which is really nice). 它还允许您使用{} -construction轻松地在日志字符串中插入对象而不会产生开销,如果该字符串实际上并未实际记录(这非常好)。

I'll suggest you consider adapting the "Simple" backend to your needs since it probably provides 90% of what you want. 我建议你考虑根据你的需要调整“简单”后端,因为它可能提供你想要的90%。

http://www.slf4j.org/apidocs/org/slf4j/impl/SimpleLogger.html http://www.slf4j.org/apidocs/org/slf4j/impl/SimpleLogger.html

Note: Do not use any backend directly (like log4j or java.util.logging) as it will essentially lock your code to that backend. 注意:不要直接使用任何后端(如log4j或java.util.logging),因为它基本上会将代码锁定到该后端。 Use a facade. 使用立面。

Don't you like java.util.logging.Logger? 你不喜欢java.util.logging.Logger吗? It is included into JDK, you don't need anything else. 它包含在JDK中,您不需要任何其他内容。

You ask three questions: 你问三个问题:

  • What are best practices to make this logging better? 使这种日志记录更好的最佳做法是什么?

As others have noted, the best practice would be to replace it entirely, either with something like log4j or slf4j, or, to meet your "independence" goal, simply with java.util.Logger. 正如其他人所指出的那样,最好的做法是用log4j或slf4j之类的东西完全替换它,或者用java.util.Logger来满足你的“独立性”目标。

  • Is making your own logger even worth it? 让自己的记录器值得吗?

No, except in very specialized circumstances, where for some reason, the existing frameworks don't meet your needs. 不,除非在非常特殊的情况下,由于某种原因,现有的框架不能满足您的需求。 You've said nothing to indicate that that might be the case. 你没有说什么表明可能是这种情况。

  • Will the use of this logger make my framework worse than choosing something existing (like log4j)? 使用这个记录器会使我的框架比选择现有的东西(比如log4j)更糟糕吗?

Yes, if for no other reason than that it will make other maintainers spend a few minutes reading your logging class when they come into your codebase. 是的,如果没有其他原因,那么当其他维护人员进入您的代码库时,会花几分钟时间阅读您的日志记录类。 Using an existing framework means they already know what it does. 使用现有框架意味着他们已经知道它的作用。

Use log4j. 使用log4j。 It is not a heavy weight logging framework, what do you mean by "independent as much as it can be"? 它不是一个重量级的日志框架,你是什么意思“尽可能独立”?
Just add the log4j jar to your framework and you are good to go. 只需将log4j jar添加到您的框架中即可。

没有什么比使用java.util.logging.Logger更轻量级了,因为它已经在JRE中可用了。

Why re-invent the wheel? 为什么重新发明轮子?

If you use the Java util logging library then it's already in the JDK and so you have no extra code to provide. 如果您使用Java util日志库,那么它已经在JDK中,因此您无需提供额外的代码。

Otherwise, log4j is surely pretty good. 否则,log4j肯定相当不错。

I would agree with the other comments - use a COTS tool (either Logger, Log4j or other). 我同意其他评论 - 使用COTS工具(Logger,Log4j或其他)。 Writing and maintaining your own is (usually) not worth it. 编写和维护自己的(通常)不值得。

One more point to consider: If your framework contains other 3rd party software that you'd like integrated into one log file, you'd have to use some shared tool (eg the one supported by that 3rd party software). 还有一点需要考虑:如果您的框架包含您希望集成到一个日志文件中的其他第三方软件,则必须使用一些共享工具(例如,该第三方软件支持的工具)。 It is often very helpful to have all pieces of the system consolidate logs into one place. 让系统的所有部分将日志合并到一个地方通常非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM