开发者

Add a element in a non static object from a static method?

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" wr开发者_高级运维iteTo="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 static member to MyClass, like this:

public class MyClass
{
    public static ListView MyListView { get; set; }

    public static void LogMethod(string level, string message)
    {
        Console.WriteLine("l: {0} m: {1}", level, message);
        var logListView = MyListView;
        if (logListView != null) {
            logListView.Items.Add(Message);
        }
        // Do some other actions
    }
}

You can set the value of MyListView from 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 Target or TargetWithLayout. You can pass any parameters necessary (e.g. the ListView instance) 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 a ListView we can refer to).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜