VB.net类库中应用log4net实现日志记录(文件形式)

来源:互联网 发布:5.10沙恩霍斯特数据 编辑:程序博客网 时间:2024/05/30 05:07

开发环境:win7+vs2010+VB.net+.net4.0

1.下载log4net (http://logging.apache.org/log4net/)

2.新建类库类项目

3.添加log4net.dll

4.添加新项log4net的XML配置文件,例如起名为:OracleLog4Helper.config,编写内容如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <!-- Register a section handler for the log4net section -->
  <configSections>
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
  </configSections>
  <log4net>
    <!-- the rollingFile Appender, which could save log to File ,and according to the configuration, when the file reach 100kb, it will save the old file to the TestLog4Net.log.1, and the TestLog4Net.log.2 and that's all-->


    <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
      <file value="OracleLog4Helper.Log" />
      <appendToFile value="true" />
      <maximumFileSize value="10KB" />
      <maxSizeRollBackups value="2" />
      <layout type=" log4net.Layout.PatternLayout">
        <conversionPattern value="%level %date %logger - %message %t%n" />
      </layout>
    </appender>


    <root>
      <!--指定日志显示级别-->
      <!--级别由高到底:OFF\FATAL\ERROR\WARN\INFO\DEBUG\ALL-->
      <level value="INFO" />
      <appender-ref ref="RollingFile" />
    </root>


    <logger name="OracleHelper.Logging">
      <level value="ERROR"/>
    </logger>
    
  </log4net>
</configuration>

5.修改解决方案下My  Project文件夹中的AssemblyInfo.vb文件,添加以下语句:

'指定log4net的配置文件的名字为:“OracleLog4Helper.config”
<Assembly: log4net.Config.XmlConfiguratorAttribute(ConfigFile:="OracleLog4Helper.config", Watch:=True)> 

6.在类库中应用log4net,定义一个日志对象并写日志语句

   '定义日志对象 OracleHelper.Logging
    'Private Shared Log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
    Private Shared Log As log4net.ILog = log4net.LogManager.GetLogger("OracleHelper.Logging")

    ''' <summary>
    ''' 关闭数据库连接
    ''' </summary>
    ''' <returns>布尔值</returns>
    ''' <remarks>成功关闭返回true;否则返回false</remarks>
    Public Function ConnClose() As Boolean
        Try
            If Conn.State <> ConnectionState.Closed Then
                Conn.Close()
                Conn.Dispose()
                Conn = Nothing
                Log.Info("数据库关闭连接成功!")
                Return True
            End If
        Catch ex As Exception
            '写日志
            Log.Error("数据库关闭连接失败!")
        End Try
        Return False
    End Function

应用成功!对于日志的查询需求,可以利用log4net的数据库输出日志支持,编写日志查询系统。

原创粉丝点击