从app.config文件中删除日志记录查询

时间:2015-03-19 12:44:08

标签: database log4net

我正在使用Log4Net将异常记录到数据库中。它工作正常,但我必须在app.config文件中指定以下日志插入查询。

<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],
                       [Message],[Exception],[Username],,[MethodName]) 
                    VALUES (@log_date, @thread, @log_level, @logger, 
                            @message, @exception,@username,@methodname)" />

如何从配置文件中删除此查询并将其指定为代码。

我正在使用C#桌面应用程序。

1 个答案:

答案 0 :(得分:1)

像这样:

public static class LogConfigurator
{
    public static void SetCommandText(string commandText)
    {
        Hierarchy logHierarchy = log4net.LogManager.GetRepository()
                                 as Hierarchy;

        if (logHierarchy == null)
        {
            throw new InvalidOperationException(
                "Can't set command text as log4net has not been configured");
        }

        // assume there is only one appender to configure
        var appender = logHierarchy.GetAppenders()
                                   .OfType<AdoNetAppender>()
                                   .SingleOrDefault();

        if (appender == null)
        {
            throw new InvalidOperationException
                ("Can't set command text as can't locate a database appender");
        }

        appender.CommandText = commandText;
        appender.ActivateOptions();
    }
}