I am trying to implement a logging concept with AOP but while printing the log I need give my own method name instead of the default.
Update (based on the comments from @glitch):
I am using the
%M
conversion specifier to tell Logback to include the method name in each log event.I want to replce the Logback derived method name for some log events, spcifically; for the log events emitted by my AOP joinpoint.
I do not want to write the 'actual method name' somewhere else in the log event; I want the method name to be used and to be correct i.e. to represent the original method rather than the interception method.
The
%M
conversion specifier is implemented bych.qos.logback.classic.pattern.MethodOfCallerConverter
. The implementation is quite simple:So, you could provide your own implementation. Something like this perhaps ...
... which uses
MDC
to pass the actual method name from your joinpoint. In your joinpoint you would put the MDC value before invoking on the logger e.g.But ... Logback does not provide any way for you to declare your own custom converter. The converters in use by Logback are declared in a static initializer on
ch.qos.logback.classic.PatternLayout
and this is not extensible/overrideable. So, I think your options are:Create a
ch.qos.logback.classic.pattern.MethodOfCallerConverter
class in your own code base i.e. replace Logback's own MethodOfCallerConverter with your own. You could use the example I provided above and - as long as you put theCUSTOM_METHOD_NAME_KEY
value in MDC before invoking on the logger - it will do what you wantContinue to use the
%M
specifier but for AOP intercepted methods add an additional MDC attribute to display the actual method name. This would result in the Logback method name appearing in all log output with the actula method name appearing too (when available). For example:Stop using the
%M
specifier and log all method names via MDC. This would result in the correct method name appearing but it would require you to update MDC in every method (which sounds quite awkward). For example: