-
In my application I log exception using the pattern layout and provide additional information. Something like below,
I am wondering what is the best way to log exceptions? Above method can lead to high object allocation rate especially with printing full stack trace and using the pattern layout. Is there a better way and also is there some kind of throttling for logger to avoid logging exceptions at a high rate ? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
I have the same question, but after my investigation, there is no way to avoid it. |
Beta Was this translation helpful? Give feedback.
-
If you use Log4j Core as the backend for the Log4j API, the method:
does not allocate any object regardless whether the Logback on the other hand will allocate new objects. Disclaimer: I don't count as allocation the creation of new exceptions, since they will be allocated regardless whether you log them or not. Exceptions are generally heavy to create (it depends on the JVM) and should be "exceptional". If your application is generating exceptions at a high rate, you should look into the business logic. |
Beta Was this translation helpful? Give feedback.
-
@mind-fuzzy, not necessarily. If you choose a layout (e.g., As a matter of fact,
@mind-fuzzy, @tcmot, some appenders provide built-in throttling, e.g., log4j2-redis-appender. For those which don't have such a support, you can use the Log4j BurstFilter. |
Beta Was this translation helpful? Give feedback.
@mind-fuzzy, not necessarily. If you choose a layout (e.g.,
PatternLayout
,JsonTemplateLayout
) and appender combination that supports garbage-free logging and configure them right (not all configuration options are garbage-free), you will have a blazing fast logging that is not possible with any other Log4j competitors.As a matter of fact,
JsonTemplateLayout
has no allocations itself while serializing stack traces except while getting the stack trace usingThrowable#getStackTrace()
, which incurs a clone operation in JDK where no Log4j has no influence on. (Patter…