Org apache log logger java

Org apache log logger java

This is the central class in the log4j package. Most logging operations, except configuration, are done through this class.

Since: log4j 1.2 Author: Ceki Gülcü

Field Summary
Fields inherited from class org.apache.log4j.Category
additive, level, name, parent, repository, resourceBundle
Constructor Summary
protected Logger (String name)
Method Summary
static Logger getLogger (Class clazz)
Shorthand for getLogger(clazz.getName()) .
static Logger getLogger (String name)
Retrieve a logger named according to the value of the name parameter.
static Logger getLogger (String name, LoggerFactory factory)
Like getLogger(String) except that the type of logger instantiated depends on the type returned by the LoggerFactory.makeNewLoggerInstance(java.lang.String) method of the factory parameter.
static Logger getRootLogger ()
Return the root logger for the current logger repository.
boolean isTraceEnabled ()
Check whether this category is enabled for the TRACE Level.
void trace (Object message)
Log a message object with the TRACE level.
void trace (Object message, Throwable t)
Log a message object with the TRACE level including the stack trace of the Throwable t passed as parameter.
Methods inherited from class org.apache.log4j.Category
addAppender, assertLog, callAppenders, debug, debug, error, error, exists, fatal, fatal, forcedLog, getAdditivity, getAllAppenders, getAppender, getChainedPriority, getCurrentCategories, getDefaultHierarchy, getEffectiveLevel, getHierarchy, getInstance, getInstance, getLevel, getLoggerRepository, getName, getParent, getPriority, getResourceBundle, getResourceBundleString, getRoot, info, info, isAttached, isDebugEnabled, isEnabledFor, isInfoEnabled, l7dlog, l7dlog, log, log, log, removeAllAppenders, removeAppender, removeAppender, setAdditivity, setLevel, setPriority, setResourceBundle, shutdown, warn, warn
Читайте также:  Css adding content after
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Logger


getLogger

Retrieve a logger named according to the value of the name parameter. If the named logger already exists, then the existing instance will be returned. Otherwise, a new instance is created.

By default, loggers do not have a set level but inherit it from their neareast ancestor with a set level. This is one of the central features of log4j.

Parameters: name — The name of the logger to retrieve.

getLogger

Parameters: clazz — The name of clazz will be used as the name of the logger to retrieve. See getLogger(String) for more detailed information.

getRootLogger

The Logger.getName() method for the root logger always returns string value: «root». However, calling Logger.getLogger(«root») does not retrieve the root logger but a logger just under root named «root».

In other words, calling this method is the only way to retrieve the root logger.

getLogger

public static Logger getLogger(String name, LoggerFactory factory)

Like getLogger(String) except that the type of logger instantiated depends on the type returned by the LoggerFactory.makeNewLoggerInstance(java.lang.String) method of the factory parameter.

This method is intended to be used by sub-classes.

Parameters: name — The name of the logger to retrieve. factory — A LoggerFactory implementation that will actually create a new Instance. Since: 0.8.5

trace

Parameters: message — the message object to log. Since: 1.2.12 See Also: for an explanation of the logic applied.

trace

Log a message object with the TRACE level including the stack trace of the Throwable t passed as parameter.

See Category.debug(Object) form for more detailed information.

Parameters: message — the message object to log. t — the exception to log, including its stack trace. Since: 1.2.12

isTraceEnabled

public boolean isTraceEnabled()

Returns: boolean — true if this category is enabled for level TRACE, false otherwise. Since: 1.2.12

Overview Package Class Use Tree Deprecated Index Help
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Copyright © 1999-2012 Apache Software Foundation. All Rights Reserved.

Источник

Org apache log logger java

The core implementation of the Logger interface. Besides providing an implementation of all the Logger methods, this class also provides some convenience methods for Log4j 1.x compatibility as well as access to the Filters and Appenders associated with this Logger. Note that access to these underlying objects is provided primarily for use in unit tests or bridging legacy Log4j 1.x code. Future versions of this class may or may not include the various methods that are noted as not being part of the public API. TODO All the isEnabled methods could be pushed into a filter interface. Not sure of the utility of having isEnabled be able to examine the message pattern and parameters. (RG) Moving the isEnabled methods out of Logger noticeably impacts performance. The message pattern and parameters are required so that they can be used in global filters.

Nested Class Summary

Field Summary

Fields inherited from class org.apache.logging.log4j.spi.AbstractLogger

Constructor Summary

Constructors
Modifier Constructor and Description
protected Logger (LoggerContext context, String name, org.apache.logging.log4j.message.MessageFactory messageFactory)

Method Summary

This method is not exposed through the public API and is present only to support the Log4j 1.2 compatibility bridge.

This method is not exposed through the public API and is present only to support the Log4j 1.2 compatibility bridge.

Источник

Org apache log logger java

Log4j 2 API

Overview

The Log4j 2 API provides the interface that applications should code to and provides the adapter components required for implementers to create a logging implementation. Although Log4j 2 is broken up between an API and an implementation, the primary purpose of doing so was not to allow multiple implementations, although that is certainly possible, but to clearly define what classes and methods are safe to use in «normal» application code.

Hello World!

No introduction would be complete without the customary Hello, World example. Here is ours. First, a Logger with the name «HelloWorld» is obtained from the LogManager. Next, the logger is used to write the «Hello, World!» message, however the message will be written only if the Logger is configured to allow informational messages.

import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class HelloWorld < private static final Logger logger = LogManager.getLogger("HelloWorld"); public static void main(String[] args) < logger.info("Hello, World!"); >>

The output from the call to logger.info() will vary significantly depending on the configuration used. See the Configuration section for more details.

Substituting Parameters

Frequently the purpose of logging is to provide information about what is happening in the system, which requires including information about the objects being manipulated. In Log4j 1.x this could be accomplished by doing:

Doing this repeatedly has the effect of making the code feel like it is more about logging than the actual task at hand. In addition, it results in the logging level being checked twice; once on the call to isDebugEnabled and once on the debug method. A better alternative would be:

logger.debug("Logging in user <> with birthday <>", user.getName(), user.getBirthdayCalendar());

With the code above the logging level will only be checked once and the String construction will only occur when debug logging is enabled.

Formatting Parameters

Formatter Loggers leave formatting up to you if toString() is not what you want. To facilitate formatting, you can use the same format strings as Java’s Formatter. For example:

public static Logger logger = LogManager.getFormatterLogger("Foo"); logger.debug("Logging in user %s with birthday %s", user.getName(), user.getBirthdayCalendar()); logger.debug("Logging in user %1$s with birthday %2$tm %2$te,%2$tY", user.getName(), user.getBirthdayCalendar()); logger.debug("Integer.MAX_VALUE = %,d", Integer.MAX_VALUE); logger.debug("Long.MAX_VALUE = %,d", Long.MAX_VALUE);

To use a formatter Logger, you must call one of the LogManager getFormatterLogger methods. The output for this example shows that Calendar toString() is verbose compared to custom formatting:

2012-12-12 11:56:19,633 [main] DEBUG: User John Smith with birthday java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=?,YEAR=1995,MONTH=4,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=23,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,DST_OFFSET=?] 2012-12-12 11:56:19,643 [main] DEBUG: User John Smith with birthday 05 23, 1995 2012-12-12 11:56:19,643 [main] DEBUG: Integer.MAX_VALUE = 2,147,483,647 2012-12-12 11:56:19,643 [main] DEBUG: Long.MAX_VALUE = 9,223,372,036,854,775,807

Mixing Loggers with Formatter Loggers

Formatter loggers give fine-grained control over the output format, but have the drawback that the correct type must be specified (for example, passing anything other than a decimal integer for a %d format parameter gives an exception).

If your main usage is to use <>-style parameters, but occasionally you need fine-grained control over the output format, you can use the printf method:

public static Logger logger = LogManager.getLogger("Foo"); logger.debug("Opening connection to <>. ", someDataSource); logger.printf(Level.INFO, "Logging in user %1$s with birthday %2$tm %2$te,%2$tY", user.getName(), user.getBirthdayCalendar());

Java 8 lambda support for lazy logging

In release 2.4, the Logger interface added support for lambda expressions. This allows client code to lazily log messages without explicitly checking if the requested log level is enabled. For example, previously you would write:

// pre-Java 8 style optimization: explicitly check the log level // to make sure the expensiveOperation() method is only called if necessary if (logger.isTraceEnabled()) < logger.trace("Some long-running operation returned <>", expensiveOperation()); >

With Java 8 you can achieve the same effect with a lambda expression. You no longer need to explicitly check the log level:

// Java-8 style optimization: no need to explicitly check the log level: // the lambda expression is not evaluated if the TRACE level is not enabled logger.trace("Some long-running operation returned <>", () -> expensiveOperation());

Logger Names

Most logging implementations use a hierarchical scheme for matching logger names with logging configuration. In this scheme, the logger name hierarchy is represented by ‘.’ characters in the logger name, in a fashion very similar to the hierarchy used for Java package names. For example, org.apache.logging.appender and org.apache.logging.filter both have org.apache.logging as their parent. In most cases, applications name their loggers by passing the current class’s name to LogManager.getLogger(. ) . Because this usage is so common, Log4j 2 provides that as the default when the logger name parameter is either omitted or is null. For example, in all examples below the Logger will have a name of «org.apache.test.MyTest» .

package org.apache.test; public class MyTest
package org.apache.test; public class MyTest
package org.apache.test; public class MyTest

Copyright © 1999-2023 The Apache Software Foundation. All Rights Reserved.
Apache Logging, Apache Log4j, Log4j, Apache, the Apache feather logo, and the Apache Logging project logo are trademarks of The Apache Software Foundation.

Источник

Оцените статью