• 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端依赖注入的功能;

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

  • 相关阅读:
    TIOBE 11月指数:C语言居首,稳居宝座,Python直逼第二!
    毕业即失业?大学生如何分配学习时间比例,拥有完整计算机知识体系?
    用微信表情翻译表白,程序员的小浪漫,赶紧Get起来!
    趣文分享:C 语言和 C++、C# 的区别在什么地方?
    C++基础知识篇:C++ 基本语法
    盘点那些争议最大的编程观点,你是什么看法呢?
    小米死磕硬核技术,将扩招5000名工程师,多个领域会使用到C++
    Gentle guide on how YOLO Object Localization works with Keras (Part 2)
    HUMBLE YOLO IMPLEMENTATION IN KERAS
    Training and Detecting Objects with YOLO3
  • 原文地址:https://www.cnblogs.com/hyd309/p/9015338.html
Copyright © 2020-2023  润新知