Java Logging

来源:互联网 发布:什么叫淘宝刷流量 编辑:程序博客网 时间:2024/06/06 16:58

1 Java Logging API

The logging API helps you gain insight into program behavior.
Here are the principal advantages of the API:

  • Easy to suppress all log records or just those below a certain level
  • Log records can be directed to different handlers
  • Both loggers and handlers can flter records
  • Log records can be formatted in different ways
  • Applications can use multiple loggers, with hierarchical names such as com.mycompany.myapp.
  • By default, the logging confguration is controlled by a confguration fle

Lets take a closer look in a log file with xml formatting

<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE log SYSTEM "logger.dtd"><log>    <record>      <date>2017-09-29T10:12:55</date>      <millis>1506651175156</millis>      <sequence>0</sequence>      <logger>logging</logger>      <level>FINER</level>      <class>ImageViewerFrame</class>      <method>&lt;init&gt;</method>      <thread>15</thread>      <message>ENTRY</message>    </record>    ...</log>

The key elements of java.util.logging package include:

  • Logger: The main entity on which applications make logging calls.
  • LogRecord: Used to pass logging requests between the logging framework and individual log handlers.
  • Handler: Exports LogRecord objects to a variety of destinations including memory, output streams, consoles, files, and sockets.
  • Level: Defines a set of standard logging levels that can be used to control logging output.
  • Filter: Provides fine-grained control over what gets logged, beyond the control provided by log levels.
  • Formatter: Provides support for formatting LogRecord objects.

1.1 Logger

Call the Logger.getLogger method to create or retrieve a logger:

private static final Logger myLogger = Logger.getLogger("com.mycompany.myapp");

注1:A logger that is not referenced by any variable can be garbage collected. To prevent this, save a reference to the logger with a static variable.

注2:Similar to package names, logger names are hierarchical. In fact, they are more hierarchical than packages. Logger parents and children share certain properties.

Call the log method to log

logger.log(Level.FINE, message);

1.2 Level

There are seven logging levels:

  • SEVERE
  • WARNING
  • INFO
  • CONFIG
  • FINE
  • FINER
  • FINEST

By default, the top three levels are actually logged.
You can set a different level

logger.setLevel(Level.FINE);

There are logging methods for all levels, such as

logger.warning(message);logger.fine(message);

1.3 LogRecord

LogRecord encapsulates all about a log

  1. date — event time
  2. millis — event time in milliseconds since 1970
  3. sequence — the sequence number
  4. logger — the source Logger’s name
  5. level — the logging message level
  6. class — the name of the class that (allegedly) issued the logging request
  7. method — the name of the method that (allegedly) issued the logging request
  8. thread — an identifier for the thread where the message originated
  9. message — the “raw” log message, before localization or formatting

The default log record shows the name of the class and method that contain the logging call.
However, if the virtual machine optimizes execution, accurate call information may not be available.
You can use the logp method to give the precise location of the calling class and method.

void logp(Level l, String className, String methodName, String message)

There are convenience methods for tracing execution flow:

void entering(String className, String methodName)void entering(String className, String methodName, Object param)void entering(String className, String methodName, Object[] params)void exiting(String className, String methodName)void exiting(String className, String methodName, Object result)

1.4 Handlers

A Handler object takes log messages from a Logger and exports them.
Like loggers, handlers have a logging level.
For a record to be logged, its logging level must be above the threshold of both the logger and the handler.

By default, a logger sends records both to its own handlers and the handlers of the parent.
The primordial logger (with name “”) sends all records with level INFO and above to the console.
To send log records elsewhere, add another handler like FileHandler.

FileHandler

The FileHandler can either write to a specified file, or it can write to a rotating set of files.
For a rotating set of files, as each file reaches a given size limit, it is closed, rotated out, and a new file opened.
Successively older files are named by adding “0”, “1”, “2”, etc. into the base filename.
By default each FileHandler is initialized using the following LogManager configuration properties.

  • FileHandler.level,specifies the default level for the Handler (defaults to Level.ALL).
  • FileHandler.filter,specifies the name of a Filter class to use (defaults to no Filter).
  • FileHandler.formatter,specifies the name of a Formatter class to use (defaults to java.util.logging.XMLFormatter)
  • FileHandler.encoding, the name of the character set encoding to use (defaults to the default platform encoding).
  • FileHandler.limit, specifies an approximate maximum amount to write (in bytes) to any one file. (Defaults to no limit,0).
  • FileHandler.count, specifies how many output files to cycle through (defaults to 1).
  • FileHandler.pattern, specifies a pattern for generating the output file name. (Defaults to “%h/java%u.log”).
  • FileHandler.append, specifies whether the FileHandler should append onto any existing files (defaults to false).
  • FileHandler.maxLocks, specifies the maximum number of concurrent locks held by FileHandler (defaults to 100).

1.5 Filters

By default, records are fltered according to their logging levels.
Each logger and handler can have an optional filter to perform additional filtering.
The Filter interface is a Functional Interface, So you can apply lambda expression.

@FunctionalInterfacepublic interface Filter {       public boolean isLoggable(LogRecord record);}

To install a filter into a logger or handler, simply call the setFilter method.

Filtering by level, only issue the info level

public class Application {    public static void main(String[] args) {        Logger logger = Logger.getLogger("ApplicationLogger");        // 匿名内部类实现        // logger.setFilter(new Filter() {        // @Override        // public boolean isLoggable(LogRecord record) {        //        // return record.getLevel()==Level.INFO;        // }        // });        // lambda 实现,简洁明了        logger.setFilter(record -> record.getLevel() == Level.INFO);        logger.info("info message ...");        logger.warning("warning message ...");        logger.severe("severe message ...");    }}

1.6 Formatters

The ConsoleHandler and FileHandler classes emit the log records in text and XML formats.
However, you can define your own formats as well.
You need to extend the Formatter class and override the format method.
In the format method, you can call the method formatMessage to localize and format the message string.
Finally, call the setFormatter method to install the formatter into the handler.

public class Application {    public static void main(String[] args) {        Logger logger = Logger.getLogger("ApplicationLogger");          ConsoleHandler handler=new ConsoleHandler();        handler.setFormatter(new Formatter() {            @Override            public String format(LogRecord record) {                                return record.getMessage();            }                   });        logger.addHandler(handler);        logger.info("新的log来了!!!\n");    }}

上面的输出结果是这样的:

新的log来了!!!
九月 29, 2017 9:15:28 下午 application.Application main
信息: 新的log来了!!!

By default, a logger sends records both to its own handlers and the handlers of the parent.
The log records firstly were sent to the ConsoleHandler you defined , this handler will apply the format method which only export the message of a log.
Then, the log records were sent to the parent handler, StreamHandler, it will apply the default log configure properties.

1.7 Manager Confguration

The good practice is changing the properties of the logging system by editing a confguration fle.
The default confguration fle is located at jre/lib/logging.properties.
Lets take a closer look :

handlers= java.util.logging.ConsoleHandler# To also add the FileHandler, use the following line instead.#handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandler.level= INFOjava.util.logging.FileHandler.pattern = %h/java%u.logjava.util.logging.FileHandler.limit = 50000java.util.logging.FileHandler.count = 1java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatterjava.util.logging.ConsoleHandler.level = INFOjava.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter# java.util.logging.SimpleFormatter.format=%4$s: %5$s [%1$tc]%n# Provides extra control for each logger. # For example,set the com.xyz.foo logger to only log SEVERE messages:com.xyz.foo.level = SEVERE

2 Log4j

see :
百度百科:log4j
or:
Apache Log4j

原创粉丝点击