Asela
Asela

Reputation: 5821

Is it fine to do logs in java class with thread id?

When we add logs in to the java class (using log4j), Is it fine to add thread id with that log messages? is it a bad practice? My idea was to add this thread id; Once we examine a log file of a multithreaded application, it is difficult to find out the correct flow using logs. (As an example, say authentication flow). Is there any better approach for this rather than logging thread id?

Upvotes: 2

Views: 2082

Answers (4)

SpaceTrucker
SpaceTrucker

Reputation: 13556

Log4j already supports the thread name using t placeholder in its pattern layout. So this is a supported feature that you should use if you find it useful. This way you don't need to pass the thread name manually. However it doesn't make use of the thread ID. So you should give meaningful names to your threads. This should be preferred as it is more indicative to what is going on in your application than just plain thread ids.

Upvotes: 4

Manish Doshi
Manish Doshi

Reputation: 1193

Logback has a special appender called SiftingAppender which provides a very nice solution to the type of problems you describe. A SiftingAppender can be used to separate (or sift) logging according to any runtime attribute, including thread id

If your concern is about several JVMs writing to the same FileAppender, then i'd suggest two things:

  • using SLF4J as a logging facade
  • using logback as logging implementation, in prudent mode

In prudent mode, FileAppender will safely write to the specified
file, even in the presence of other FileAppender instances running in different JVMs, potentially running on different hosts.

Refer this: http://logback.qos.ch/manual/appenders.html#SiftingAppender

Upvotes: 0

Linus
Linus

Reputation: 950

If you are using Java Logger API - LogRecord has method getThreadID() and can be configured to log.

For log4j there are no ThreadId methods available and No harm in logging it. In cases If your class inherits from Thread, you can use methods getName and setName to name each thread. Otherwise you could just add a name field to MyTask, and initialize it in your constructor And use a more sensible Thread Name instead of ID.

Upvotes: 0

lkamal
lkamal

Reputation: 3938

If it is the thread id, please refer this answer

However if you only need the thread name, you can use the t pattern configuration, please refer here.

Upvotes: 0

Related Questions