I know how to use nlog to log my information in a file but now I would like to redirect my log to a ListView (C#) and do some actions. So I directed my log to a method as explained in the documentation nlog. It works.
<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="msgbox" xsi:type="MethodCall" className="SomeNamespace.MyClass, MyAssembly" methodName="LogMethod">
<parameter layout="${level}" />
<parameter layout="${message}" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="msgbox" />
</rules>
</nlog>
Console.WriteLine works. It’s not my problem.
namespace SomeNamespace
{
using System;
public class MyClass
{
public static void LogMethod(string level, string message)
{
Console.WriteLine("l: {0} m: {1}", level, message);
// logListView.Items.Add(Message);
// Do some other actions
}
}
}
I would like to add a line to my logListView (see commented line) but I can’t because logListView is not static. How so? How do I proceed ?
One solution would be to add a
staticmember to MyClass, like this:You can set the value of
MyListViewfrom some other part of your application when it is available.While this solution would work, I would not prefer it because it is counter-intuitive. What you are doing here is declaring in static configuration a log target that is not meaningful at all in a static context: you want to log to a UI control that has not been created, there is no good way to refer to it until the application’s UI has been shown, and the UI will be shown at some point or (academically speaking) maybe not at all.
I believe it is preferable to create your own log target class deriving from
TargetorTargetWithLayout. You can pass any parameters necessary (e.g. theListViewinstance) to the log target’s constructor, and add the log target programmatically at the point where the values of these parameters become known (i.e. the UI is shown and we have aListViewwe can refer to).