Custom Layout Rendering

2 messages Options
Embed this post
Permalink
mvezzalini

Custom Layout Rendering

Reply Threaded More More options
Print post
Permalink
(This post was updated on )
Hello everybody,
does any of you know how to pass custom data to a custom layout renderer?
All of the NLog examples I have found about custom layout rendering only seem to manage built-in data (such as stacktrace, datetime, server name etc.).
What I would like to implement is a Logger.Write function taking addictional custom parameters such as "category" to be rendered in my log entry, something like this:

Log.Info("Application start" /* ${message} */, "System" ${category});

The goal is a correct handling of the custom argument 'category' in the following configuration:

            DatabaseTarget target = new DatabaseTarget();
            target.DBProvider = "mssql";
            target.DBHost = ".";
            target.DBUserName = "nloguser";
            target.DBPassword = "pass";
            target.DBDatabase = "databasename";
            target.CommandText = "insert into LogTable(time_stamp,level,message,category) values(@time_stamp, @level, @message, @category);";

            target.Parameters.Add(new DatabaseParameterInfo("@time_stamp", "${date}"));
            target.Parameters.Add(new DatabaseParameterInfo("@level", "${level}"));
            target.Parameters.Add(new DatabaseParameterInfo("@message", "${message}"));
            target.Parameters.Add(new DatabaseParameterInfo("@category", "${category}"));

Should I inherit from LogEventInfo class with the consequence of having to re-write every log-writing function?
Any help would be appreciated.
Thank you

Monica
mvezzalini

Re: Custom Layout Rendering

Reply Threaded More More options
Print post
Permalink
Hello, I found the answer myself.
EventContext layoutrenderer will do the trick:

            // target configuration
     DatabaseTarget target = new DatabaseTarget();
            [....] //target configuration
            target.CommandText = "insert into LogTable(time_stamp,level,message,category) values(@time_stamp, @level, @message, @category);";
            [....] //common parameters
            target.Parameters.Add(new DatabaseParameterInfo("@category", "${event-context:item=category}"));

            //runtime logging:
 NLog.Logger theLog =  NLog.LogManager.GetLogger("Example");
            NLog.LogEventInfo theEvent = new NLog.LogEventInfo(NLog.LogLevel.Trace, "", "This is my log message");
            theEvent.Context["category"] = "12345";
            theLog.Log(theEvent);

I hope this can be useful to any of you.
Anyway I agreee with Jamison (http://n2.nabble.com/event-context-needs-more-documentation-td1685980.html#a1685980) saying that EventContext is a very powerful layout renderer and therefore needs more documentation.

CHEERS