c# - NLog namespace.name from other class -


currently have logwrapper class initializes nlog , sends info/debug/warning , so.

so each method in other class starts

logwrapper.informational(string.format(" {0} starts {1}", methodbase.getcurrentmethod().declaringtype.name, methodbase.getcurrentmethod().name)); 

when in logwrapper:

private static readonly logger s_log = logmanager.getcurrentclasslogger();  public static void informational(string fmt, exception exception) {     s_log.info("{0} {1}",fmt, exception.tostring()); } 

problem since calling class different 1 accessing log wrapper log shows namespace.methodname of logwrapper useless calls methodbase made.

is there way call function class different class accessing nlog ?

thanks

if interested in using nlog wrapper still being able maintain callsite information, see answer earlier question here:

nlog callsite wrong when wrapper used

in brief, can use nlog log method , pass type of wrapper. then, if use nlog callsite layoutrenderer, nlog able figure out callsite information without having figure out yourself.

so, logwrapper might have method this:

public static void informational(string fmt, exception exception) {   logeventinfo le = new logeventinfo(loglevel.info, logger.name, null, fmt, exception.tostring());   logger.log(typeof(logwrapper), le); } 

the key passing type of wrapper (typeof(logwrapper)) first argument logger.log. nlog uses value traverse call stack until sees type declaringtype of current methodinfo. nlog treats stack frame last stack frame before actual callsite, nlog goes 1 more level after seeing it.

you should know nlog has exception layoutrenderer, don't have use exception.tostring() yourself.

while question daniel hilgarth linked in comment has interesting code, think should careful adding bunch of code determine information nlog can "free". if need logging purposes, recommend letting nlog figure out you. if need other purpose, have no choice figure out yourself.

on side note, recommend not making logging calls using style:

logwrapper.informational(string.format(" {0} starts {1}",        methodbase.getcurrentmethod().declaringtype.name, methodbase.getcurrentmethod().name)); 

if logwrapper.informational method delegates down nlog's logger.info, doing work in case logging not turned on or if logging level less info (e.g. warn, error, fatal). if, due current logging level settings, statement not logged, still formatting string , making 2 relatively expensive calls callsite information.


Comments