zoukankan      html  css  js  c++  java
  • Net Core 控制台程序使用Nlog 输出到log文件

    using CoreImportDataApp.Common;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using System;
    using CoreImportDataApp.Services;
    using NLog;//NLog.Extensions.Logging  和NLog.Web.AspNetCore两个类库。
    using Microsoft.Extensions.Logging;
    using Microsoft.AspNetCore.Hosting;
    
    namespace CoreImportDataApp
    {
        class Program
        {
            public static string SqlConnecting { get; set; }
            static void Main(string[] args)
            {
                /**
                 * 在ASP.NET Core中使用依赖注入中使用很简单,只需在Startup类的ConfigureServices()方法中,
                 * 通过IServiceCollection接口进行注入即可,其它的无需关心
                 * 
                 * 在控制台程序中就不一样了,除了注入外,你还需要构建容器,解析注入。
                 * 注入通过IServiceCollection接口,而构建容器需要调用IServiceCollection的扩展方法BuildServiceProvider(),
                 * 解析需要调用IServiceProvider的扩展方法GetService<T>()
                 **/
                var builder = new ConfigurationBuilder()
                    .AddJsonFile("appSetting.json");
                var configuration = builder.Build();
    
                SqlConnecting = configuration.GetConnectionString("DefaultConnection");
    
                IServiceCollection services = new ServiceCollection();
                services.AddOptions();
                services.Configure<TableStoreModel>(configuration.GetSection("TableStore"));
                services.AddSingleton<TableStoreModel>();
                services.AddTransient<ILoggerFactory, LoggerFactory>();
                services.AddTransient<ITest, Test>();
    
                IServiceProvider serviceProvider = services.BuildServiceProvider();
    
                TestDI testDI = new TestDI(serviceProvider);
                testDI.StartWork();
                var host = new WebHostBuilder().UseKestrel().UseStartup<Startup>().Build();
                host.Run();
                Console.ReadLine();
            }
        }
    }
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Logging;
    using NLog.Extensions.Logging;
    using NLog.Web;
    
    namespace CoreImportDataApp
    {
        public class Startup
        {
            public static NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
            public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
                loggerFactory.AddNLog();
                env.ConfigureNLog("nlog.config");
                app.Run(context=>
                {
                    return context.Response.WriteAsync("bido-Nlog");
                });
            }
        }
    }
    using Microsoft.Extensions.Logging;
    using System;
    using System.Collections.Generic;
    using System.Text;
    using NLog;
    using NLog.Extensions.Logging;
    
    namespace CoreImportDataApp.Services
    {
        public class Test:ITest
        {
            public string Add()
            {
                Startup.log.Info("运行中....");
                return "ITest => test /add()";
            }
        }
    }
    <?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="Warn"
          internalLogFile="c:	empinternal-nlog.txt">
    
      <!-- define various log targets -->
      <targets>
        <!-- write logs to file -->
        <target xsi:type="File" name="allfile" fileName="D:ProjectCodeC#TestNetCore
    etcoreWebApiBidoCoreApiCoreImportDataAppinlogs
    log-all${shortdate}.log"
                     layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />
    
    
        <target xsi:type="File" name="ownFile-web" fileName="D:ProjectCodeC#TestNetCore
    etcoreWebApiBidoCoreApiCoreImportDataAppinlogs
    log-own${shortdate}.log"
                 layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|  ${message} ${exception}" />
    
        <target xsi:type="Null" name="blackhole" />
      </targets>
    
      <rules>
        <!--All logs, including from Microsoft-->
        <logger name="*" minlevel="Warn" writeTo="allfile" />
    
        <!--Skip Microsoft logs and so log only own logs-->
        <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
        <logger name="*" minlevel="Debug" writeTo="ownFile-web" />
        <!--Trace Debug Info Warn ERROR Fatal-->
      </rules>
    </nlog>

    以上是在网上综合找到的结果;

    但是总感觉 投机取巧的使用了web端依赖注入的功能;

    各位请吐槽。。有什么高见尽管留言,看到后一一回复

  • 相关阅读:
    WITH HINDSIGHT
    圆桌最后冲刺
    圆桌总结
    圆桌十日冲刺之⑨
    圆桌十日冲刺之八
    圆桌十日冲刺之七
    圆桌十日冲刺之六
    【09NOIP提高组】Hankson 的趣味题(信息学奥赛一本通 1856)(洛谷 1072)
    灯泡(信息学奥赛一本通 1438)
    最大公约数(信息学奥赛一本通 1627)
  • 原文地址:https://www.cnblogs.com/hyd309/p/9015338.html
Copyright © 2011-2022 走看看