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?
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.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With