asp.net core-配置

配置文件的使用

asp.net core中默认配置文件是appsettings.json,可以通过IConfiguration来获取,IConfiguration可以从startup的构造函数通过DI获取

这边有3种方式来使用appsettings.json里面的配置,该配置不区分大小写

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Information"
    }
  },
  "AllowedHosts": "*"
}

 

1.直接使用字符串,冒号表示下一层级

var default= configuration["Logging:LogLevel:Default"];

2. 绑定配置模型对象

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //绑定配置模型对象
    var appSetting = new AppSetting();
    _configuration.Bind(appSetting);

    // 部分绑定
    var logging = new LogLevel();
    _configuration.GetSection("logging").Bind(logging);

    app.Run(async context =>
    {
        var a = appOptions.Logging.LogLevel.Default;
        var b = logging.LogLevel.Default;
    }
}

 

3. 通过注册服务

根据配置结构定义相关model,类似于ORM映射

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<AppSetting>(_configuration);
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptions<AppSetting> appOptions)
{
    app.Run(async context =>
    {
        var a = appOptions.Logging.LogLevel.Default;
    }
}

假如需要使用其他配置文件,比如添加了一个test.config配置文件,这个config就可以跟IConfiguration一样用了

public void ConfigureServices(IServiceCollection services)
{
    var config = new ConfigurationBuilder().AddJsonFile("test.json").Build();
}

 

NLog和Log4Net的使用

asp.net core内置了日志组件,可以在控制台,页面输出信息,但是不支持写入文件,所以我们需要使用第三方的日志组件。

NLog和Log4Net是两款比较常用的日志组件,他们是专门用于.net的,实现了.net的内置接口,这意味着你可以像调用.net内置日志组件一样调用它。

首先介绍下日志个级别,从低到高如下

     //
    // Summary:
    //     Defines logging severity levels.
    public enum LogLevel
    {
        //
        // Summary:
        //     Logs that contain the most detailed messages. These messages may contain sensitive
        //     application data. These messages are disabled by default and should never be
        //     enabled in a production environment.
        Trace = 0,
        //
        // Summary:
        //     Logs that are used for interactive investigation during development. These logs
        //     should primarily contain information useful for debugging and have no long-term
        //     value.
        Debug = 1,
        //
        // Summary:
        //     Logs that track the general flow of the application. These logs should have long-term
        //     value.
        Information = 2,
        //
        // Summary:
        //     Logs that highlight an abnormal or unexpected event in the application flow,
        //     but do not otherwise cause the application execution to stop.
        Warning = 3,
        //
        // Summary:
        //     Logs that highlight when the current flow of execution is stopped due to a failure.
        //     These should indicate a failure in the current activity, not an application-wide
        //     failure.
        Error = 4,
        //
        // Summary:
        //     Logs that describe an unrecoverable application or system crash, or a catastrophic
        //     failure that requires immediate attention.
        Critical = 5,
        //
        // Summary:
        //     Not used for writing log messages. Specifies that a logging category should not
        //     write any messages.
        None = 6
    }

 

Nlog使用

首先nuget添加相应的包,.net core下需要NLog包,假如需要在asp.net core下,还需要下载另一个NLog.Web.AspNetCore包。

然后添加配置文件nlog.config,直接从官网获取就行,有一点要注意官网的路径是\来划分,但是linux下只能用/才能定位。所以我们统一改成/,这样windows和linux下都能使用

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Info"
      internalLogFile="${basedir}/logs/internal-nlog.txt">

  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <!-- the targets to write to -->
  <targets async="true">
    <!-- write logs to file  -->
    <target xsi:type="File" name="allfile" fileName="${basedir}/logs/nlog-all-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

    <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
    <target xsi:type="File" name="ownFile-web" fileName="${basedir}/logs/nlog-own-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|Ip: ${aspnet-Request-Ip}|action: ${aspnet-mvc-action}" />

  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--Skip non-critical Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" maxlevel="Info" final="true" />
    <!-- BlackHole without writeTo -->
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>

 

然后在构造函数中通过DI获取ILogger<类名> logger,在哪个类里面使用,就把相应的类名添加到<>中。

使用就更简单了,使用logger.LogInformation等方法,每个方法对应了日志记录等级

 

log4Net用法

Nuget添加log4net库,

然后添加log4net.config,名字无所谓

<log4net>
    <logger name="ApplicationLogger">
        <level value="INFO" />
        <appender-ref ref="Application" />
        <appender-ref ref="Debug" />
    </logger>
    <appender name="Application" type="log4net.Appender.RollingFileAppender">
        <file type="log4net.Util.PatternString" value="logs\Application" />
        <appendToFile value="true" />
        <rollingStyle value="date" />
        <maxSizeRollBackups value="10" />
        <maximumFileSize value="10MB" />
        <staticLogFileName value="false" />
        <datePattern value="yyyyMMdd'.log'"/>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date - [%-10level] - [%-20sourceType] - %message%newline" />
        </layout>
    </appender>
    <appender name="Debug" type="log4net.Appender.DebugAppender">
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date - [%-10level] - [%-20sourceType] - %message%newline" />
        </layout>
    </appender>
</log4net>

将log4net.config的属性改成始终复制,意思是这个配置文件始终会复制到文件夹中

 

 

 使用如下

    class Program
    {
        static void Main(string[] args)
        {
            ILoggerRepository repository = LogManager.CreateRepository("myLogRepository");
            XmlConfigurator.Configure(repository, new FileInfo("log4net.Config"));
            ILog log = LogManager.GetLogger(repository.Name, "ApplicationLogger");
            log.Info("ffffffffffffffff");
        }
    }

 

posted @ 2021-01-07 10:24  小鸡蛋白  阅读(242)  评论(0编辑  收藏  举报