Skip to content

使用

RsCode使用的是Log4Net记录日志,可将日志记录至文件和数据库中,精准定位错误位置;当前log4net版本2.0.15

RsCode中日志使用步骤:

  1. 引用RsCode

  2. log4net配置文件log4net.config到项目中, 具体的配置文件查看文章结尾附录1

  3. 添加Log4Net服务

    3.1 打开Program.cs文件,配置log4net服务

    csharp
    using Microsoft.Extensions.Logging;
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        //添加log4net日志
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddLog4Net();
        })
        .ConfigureWebHostDefaults(webBuilder =>
                                  {
                                      webBuilder.UseStartup<Startup>();
                                  });

    csharp
    var builder=WebApplication.CreateBuilder(args);
    builder.Logging.AddLog4Net();

    3.2 添加日志记录服务

    csharp
    services.AddExceptionLogging();

    csharp
    builder.Services.AddExceptionLogging();

    调用异常处理中间件

    csharp
    app.UseRouting();
    app.UseErrorHandler();
    app.UseAuthentication();
    app.UseAuthorization();

    该中间件可将ajax请求和url以/api开头的请求,响应结果以json格式输出

  4. 开始使用

    以下两种方式都可以

    4.1 使用方式一:注入的方式记录日志

    csharp
    using Microsoft.Extensions.Logging;
    ILogger logger; 
    public HomeController(ILogger<HomeController>  _logger)
    {
        logger = _logger;
    }
    
    public IActionResult Index()
    {
        logger.LogInformation("开始记日志了");
        return View();
    }

    4.2 使用方式二:使用LogHelper记录日志

    csharp
    using RsCode;
    LogHelper.WriteLog("message");//记录日志,等级ERROR

    LogHelper使用log4net封装,其接口定义

    csharp
    void WriteLog(string logContent);
    void WriteLog(string logContent, Log4NetLevel log4Level);
    void WriteLog(Type type,Exception ex);
    void WriteLog(Type type, string logContent, Log4NetLevel log4Level,Exception ex=null);

    项目下创建文件log4net.config,复制以下内容到项目中

注意

log4net.cofig 日志配置中关于日志文件的输出位置

1.windows环境时,是\log\info\

2.linux环境时 /log/info/

附录1

附录1 log4net.config文件内容:

log4net文件内容,默认即写入文件又写入数据库,根据root节点进行调整,例:不写入数据库就删除这一行 <appender-ref ref="AdoNetAppender_MySql" />

xml
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
 <!--数据日志-->
  <appender name="InfoRollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <param name="File" value="Log\Info\" />
    <param name="AppendToFile" value="true" />
    <param name="rollingStyle" value="Date" />
    <param name="datePattern" value="yyyy-MM-dd.'Info.log'" />
    <param name="staticLogFileName" value="false" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%n%n%n 记录时间:%date %n日志级别:  %-5level %n类型:%logger  %n日志描述:%message %newline%newline" />
    </layout>
    <filter type="log4net.Filter.LevelRangeFilter">
      <param name="LevelMin" value="INFO" />
      <param name="LevelMax" value="INFO" />
    </filter>
  </appender>
  <!--错误日志-->
	<appender name="ErrorRollingFileAppender" type="log4net.Appender.RollingFileAppender">
		<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
		<param name="file" value="Log\Error\" />
		<param name="appendToFile" value="true" />
		<param name="rollingStyle" value="Date" />
		<param name="datePattern" value="yyyy-MM-dd.'error.log'" />
		<param name="staticLogFileName" value="false" />
		<layout type="log4net.Layout.PatternLayout">
			<conversionPattern value="%n%n%n 记录时间:%date %n日志级别:  %-5level %n出错类:%logger  %n错误信息:%message %newline%newline" />
		</layout>
		<filter type="log4net.Filter.LevelRangeFilter">
			<param name="LevelMin" value="ERROR" />
			<param name="LevelMax" value="ERROR" />
		</filter>
	</appender>
  <!--调试日志-->
  <appender name="DebugRollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <param name="File" value="Log\Debug\" />
    <param name="AppendToFile" value="true" />
    <param name="rollingStyle" value="Date" />
    <param name="datePattern" value="yyyy-MM-dd.'debug.log'" />
    <param name="staticLogFileName" value="false" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%n%n%n 记录时间:%date %n日志级别:  %-5level %n类型:%logger  %n调试信息:%message %newline%newline" />
    </layout>
    <filter type="log4net.Filter.LevelRangeFilter">
      <param name="LevelMin" value="DEBUG" />
      <param name="LevelMax" value="DEBUG" />
    </filter>
  </appender>
	
	<appender name="AdoNetAppender_MySql" type="log4net.Appender.ADONetAppender">
		<!--日志缓存写入条数 设置为0时只要有一条就立刻写到数据库-->
		<bufferSize value="1" />
		<!--日志数据库连接串-->
		<connectionType value="MySql.Data.MySqlClient.MySqlConnection, MySql.Data" />
		<connectionString value="server=127.0.0.1;uid=root;pwd=123456;port=3306;pooling=True;database=rswl_pan;" providerName="MySql.Data.MySqlClient;" />
		<!--数据库连接断开时重新连接-->
		<param name="ReconnectOnError" value="true"/>
		<!--日志数据库脚本-->
		<commandText value="INSERT INTO rscode_system_log(LogDate,Thread,LogLevel,Logger,LogMessage,ExceptionData) VALUES (@log_date,@thread,@log_level,@logger,@message,@exception)" />
		<parameter>
			<parameterName value="@log_date" />
			<dbType value="DateTime" />
			<layout type="log4net.Layout.RawTimeStampLayout" />
		</parameter>
		<parameter>
			<parameterName value="@thread" />
			<dbType value="String" />
			<size value="50" />
			<layout type="log4net.Layout.PatternLayout" value="%thread"/>
				 
		</parameter>
		<parameter>
			<parameterName value="@log_level" />
			<dbType value="String" />
			<size value="20" />
			<layout type="log4net.Layout.PatternLayout" value="%-5level" /> 
		</parameter>
		<parameter>
			<parameterName value="@logger" />
			<dbType value="String" />
			<size value="255" />
			<layout type="log4net.Layout.PatternLayout" value="%logger" /> 
		</parameter>
		<parameter>
			<parameterName value="@message" />
			<dbType value="String" />
			<size value="4000" />
			<layout type="log4net.Layout.PatternLayout" value="%message" /> 
		</parameter>
		<parameter>
			<parameterName value="@exception" />
			<dbType value="String" />
			<size value="2000" />
			<layout type="log4net.Layout.ExceptionLayout"/>
		</parameter>
    </appender>


	<root>
		<!--控制级别,由低到高: ALL|DEBUG|INFO|WARN|ERROR|FATAL|OFF-->
    <level value="INFO" />
    <!--文件形式记录日志-->
    <appender-ref ref="ErrorRollingFileAppender" />
    <appender-ref ref="DebugRollingFileAppender" />
    <appender-ref ref="InfoRollingFileAppender" />
     <!--保存文件至数据库-->   
	<appender-ref ref="AdoNetAppender_MySql" />
  </root>
</log4net>

附录2:mysql数据库脚本

sql
drop table if exists rscode_system_log;

/*==============================================================*/
/* Table: rscode_system_log                                     */
/*==============================================================*/
create table rscode_system_log
(
   Id                   bigint not null auto_increment,
   LogDate              datetime not null,
   Thread               varchar(50) not null,
   LogLevel             varchar(20) not null,
   Logger               varchar(255) not null,
   LogMessage           text not null,
   ExceptionData        text not null,
   primary key (Id)
);

默认提供了这几个字段@log_date, @thread, @log_level, @logger, @message, @exception,

其它的字段需要自己定义