是否可以使用Log4Net写入CLR存储过程中的日志文件?

时间:2011-06-15 15:23:13

标签: log4net clrstoredprocedure

问题:无法使用CLR存储过程内的Log4net调试(写入)日志文件。我正在构建CLR项目的方式可能有问题吗?我只是将DLL导入sql server(创建程序集....)。我是否还需要导入App.Config?

DLL名称: CLRTest.dll

源代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server; 
using log4net;
using log4net.Config;

public class MyClass
{
    private readonly static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    private static readonly string sContextConn = "Context Connection=true";

    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void Select1()
    {
        XmlConfigurator.Configure();
        log.Debug("Begin Select1()...");
        using (SqlConnection connection = new SqlConnection(sContextConn))
        {
            connection.Open();
            SqlCommand command = new SqlCommand("select 1", connection);
            SqlDataReader r = command.ExecuteReader();
            SqlContext.Pipe.Send(r);
        }

        log.Debug("End Select1()...");
    }
}//end MyClass

Log4Net XML Config(App.Config):

    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    </configSections>

    <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="C:\log\clrsql.log" />
      <param name="AppendToFile" value="true" />
          <datePattern value="yyyyMMdd-HHmm" />
      <param name="rollingStyle" value="Size" />
      <param name="maxSizeRollBackups" value="50" />
      <param name="maximumFileSize" value="25MB" />
      <param name="staticLogFileName" value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d %-5p [t-%t] [%c.%M(%L)] %m%n" />
      </layout>
    </appender>


    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d %-5p [%c.%M(%L)] %m%n" />
      </layout>
    </appender>

    <root>
      <level value="DEBUG" />
      <appender-ref ref="RollingFileAppender" />
      <appender-ref ref="ConsoleAppender" />
    </root>
  </log4net>

SQL Server的权限:

C:\ log \ - NETWORK SERVICE和MyDomain \ sqlserveraccount对“log”文件夹具有完全控制权。

SQL脚本:

drop procedure clr_Select1
go
drop assembly CLRTest
go
create ASSEMBLY CLRTest FROM 'C:\Share\ClrSql\TEST\CLRTest.dll' WITH PERMISSION_SET = unsafe
go
CREATE PROCEDURE clr_Select1 
    AS EXTERNAL NAME CLRTest.MyClass.Select1
go
exec clr_Select1 

SQL输出:

(无栏名)

1

1 个答案:

答案 0 :(得分:0)

您正在进行的log4net配置程序调用实际上会尝试查找AppDomain.CurrentDomain.SetupInformation.ConfigurationFile。我不知道AppDomain对于存储过程是什么。

您可能想尝试standalone配置文件并使用该配置程序的重载。

log4net.Config.XmlConfigurator.Configure(new FileInfo("config.log4net"));