Home  >  Q&A  >  body text

How to use log4j in java without declaring it every time it is called?

Every time you write a new class, you must declare it as follows:

private static Logger logger = Logger.getLogger(Test.class);  

Isn’t this very troublesome? Is there any way to set the Logger to a class that can be called statically, directly call the info, error and other methods, and at the same time print out the current class, thread number and other information?

为情所困为情所困2712 days ago596

reply all(3)I'll reply

  • 漂亮男人

    漂亮男人2017-05-17 10:06:39

    You can simply encapsulate it to achieve what you want, such as building a class to encapsulate Logger and exposing several static interfaces. As for why many codes are written as private static Logger logger = Logger.getLogger(Test.class);, it is actually mainly to improve the flexibility and accuracy of logs.

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-17 10:06:39

    Look at this /a/11...

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-17 10:06:39

    Statementlog是因为他可以定义不同的logger name可以通过logger name定制自己的输出方式, 比如level, appender...etc

    If your logs are processed in the same way, you can declare it公共的静态 log 对象, 需要的地方使用该logThere will be no duplicate declarations.
    For example:

    import static xxx.GlobalLogs.log;
    
    log.debug("...");
    log.info("...");
    //...

    Of course you can also use lombok to simplify your code.

    reply
    0
  • Cancelreply