Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a Log4J logger be declared as transient?

I am using Java 1.4 with Log4J.

Some of my code involves serializing and deserializing value objects (POJOs).

Each of my POJOs declares a logger with

private final Logger log = Logger.getLogger(getClass()); 

The serializer complains of org.apache.log4j.Logger not being Serializable.

Should I use

private final transient Logger log = Logger.getLogger(getClass()); 

instead?

like image 443
Vihung Avatar asked Sep 17 '08 11:09

Vihung


People also ask

Should loggers be static?

Loggers should be declared to be static and final. It is good programming practice to share a single logger object between all of the instances of a particular class and to use the same logger for the duration of the program.

Why do we declare logger static final?

private static final Logger log = LoggerFactory. getLogger(Foo. class); The former way allows you to use the same logger name (name of the actual class) in all classes throughout the inheritance hierarchy.

How does log4j logging work?

Log4j allows logged messages to contain format strings that reference external information through the Java Naming and Directory Interface (JNDI). This allows information to be remotely retrieved across a variety of protocols, including the Lightweight Directory Access Protocol (LDAP).

What are the three most important components of log4j?

log4j has three main components: loggers: Responsible for capturing logging information. appenders: Responsible for publishing logging information to various preferred destinations. layouts: Responsible for formatting logging information in different styles.


1 Answers

How about using a static logger? Or do you need a different logger reference for each instance of the class? Static fields are not serialized by default; you can explicitly declare fields to serialize with a private, static, final array of ObjectStreamField named serialPersistentFields. See Oracle documentation

Added content: As you use getLogger(getClass()), you will use the same logger in each instance. If you want to use separate logger for each instance you have to differentiate on the name of the logger in the getLogger() -method. e.g. getLogger(getClass().getName() + hashCode()). You should then use the transient attribute to make sure that the logger is not serialized.

like image 175
Aleksi Yrttiaho Avatar answered Sep 22 '22 12:09

Aleksi Yrttiaho