首页 > 其他分享 >.NET控制台读取appsettings.json,配置日志

.NET控制台读取appsettings.json,配置日志

时间:2024-07-05 18:32:46浏览次数:1  
标签:GetSection Console appsettings json WriteLine var NET config true

需要安装 nuget 包 Microsoft.Extensions.Configuration 、Microsoft.Extensions.Configuration.FileExtensions 、Microsoft.Extensions.Configuration.Json、NLog

using NLog;
using NLog.Config;
using Microsoft.Extensions.Configuration;
namespace ConsoleApp2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            LogManager.Configuration = new XmlLoggingConfiguration(string.Format("{0}/NLog.config", AppDomain.CurrentDomain.BaseDirectory.ToString()));
            var logger = NLog.LogManager.GetCurrentClassLogger();
            logger.Error("打印日志");
            try
            {
                var a = Directory.GetCurrentDirectory();
                var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                                     .AddJsonFile("appsettings.json", true, true)
                                     .AddJsonFile("appsettings.Development.json", true, true)
                                     .Build();

                var baseUrl = config.GetSection("baseUrl").Value;
                var setting1 = config["compilerOptions:target"];
                var setting2 = config["compilerOptions:sourceMap"];
                var setting3 = config.GetSection("exclude").GetSection("1").Value;
                var setting4 = config.GetSection("user").GetSection("0").GetSection("name").Value;

                Console.WriteLine($"baseUrl: {baseUrl}");
                Console.WriteLine($"Setting1: {setting1}");
                Console.WriteLine($"Setting2: {setting2}");
                Console.WriteLine($"setting3: {setting3}");
                Console.WriteLine($"setting4: {setting4}");
            }
            catch (Exception ex) {
                logger.Error(ex.ToString());
            }
        }
    }
}
{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5"
  },
  "exclude": [
    "node_modules",
    "wwwroot"
  ],
  "baseUrl": "http://baidu.com",
  "user": [
    {
      "name": "张三",
      "code": 1
    },
    {
      "name": "李四",
      "code": 2
    }
  ]
}

 

<?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:\temp\internal-nlog.txt">

    <!-- 加载ASP.NET Core插件 -->
    <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
    </extensions>

    <!-- 输出目的地 -->
    <targets>
        <!-- 输出到文件,这个文件记录所有日志 -->
        <target xsi:type="File" name="allfile" fileName="${basedir}/logs/error-${shortdate}.txt"
                    layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />

        <!-- 另外一个日志记录文件,户口也跳过Microsoft开头相关日志信息 -->
        <target xsi:type="File" name="ownFile-web" fileName="${basedir}/logs/info-${shortdate}.txt"
                layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}| ${exception}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action} : ${message} " />

        <!-- write to the void aka just remove -->
        <target xsi:type="Null" name="blackhole" />
    </targets>

    <!-- 写入目的地的规则 -->
    <rules>
        <!--全部记录,包括Microsoft开头的相关日志信息-->
        <logger name="*" minlevel="Error" writeTo="allfile" />

        <!--跳过Microsoft开头的相关日志信息-->
        <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
        <logger name="*" minlevel="Info" writeTo="ownFile-web" />
    </rules>
</nlog>

 

标签:GetSection,Console,appsettings,json,WriteLine,var,NET,config,true
From: https://www.cnblogs.com/sanday/p/18286408

相关文章

  • C# 去除JSON的空节点
    方法一:usingNewtonsoft.Json.Linq;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;JObjecttestJson=newJObject(){{"code","1234560"},{"app",null}};testJson.DescendantsAndSelf().......
  • 解决nacos报错 Caused by: io.grpc.netty.shaded.io.netty.channel.unix.Errors$Nati
    报错信息:org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)atorg.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)atorg......
  • 【Unity几种数据存储之间的区别】PlayerPrefs、Json、XML、二进制、SQLite数据存储之
    ......
  • 记一次aspnetcore发布部署流程初次使用k8s
    主题:aspnetcorewebapi项目,提交到gitlab,通过jenkins(gitlab的ci/cd)编译、发布、推送到k8s。关于gitlab、jenkins、k8s安装,都是使用docker启动服务。首先新建一个项目,为了方便浏览就把swaggerr非开发环境不展示去掉 下面就是需要准备Dockerfile和k8s.yaml文件,这里不应该用......
  • Kubernetes——批量导出 Kubernetes 命名空间下的资源 Manifest 及 CRD 资源
    批量导出Kubernetes命名空间下的资源Manifest及CRD资源一、需求背景  在Kubernetes集群的日常管理和维护中,经常需要备份或迁移集群中的资源。为了高效地进行这一操作,本脚本旨在批量导出指定命名空间下的多种Kubernetes资源(如Deployment、StatefulSet、Pods、Conf......
  • 告别 .NET 7,支持将于 5 月结束——我们几乎不认识你
    微软.NET7软件框架的支持将于5月结束,这距离其2022年发布仅过去18个月——这提醒我们,长期更新时代正在成为过去。.NET7于2022年11月8日首次亮相,与其前身不同的是,它是一个标准期限支持(STS)版本,这意味着它的支持期为18个月。.NET6和.NET8都是长期支持(L......
  • 脉冲神经网络(Spiking Neural Network,SNN)相关论文最新推荐(一)
    用稀疏代理梯度直接训练时态脉冲神经网络论文链接:www.sciencedirect.comBenchmarkingArtificialNeuralNetworkArchitecturesforHigh-PerformanceSpikingNeuralNetworks论文链接:www.mdpi.comHierarchicalspikingneuralnetworkauditoryfeaturebaseddry-typet......
  • .netcore微服务——项目搭建
    在.NETCore中,微服务是一种架构风格,它将应用程序构造为一组小型服务的集合,这些服务都通过HTTP-basedAPI进行通信。每个服务都是独立部署的,可以用不同的编程语言编写,并且可以使用不同的数据存储技术。微服务的主要优点包括:增强容错能力:一个服务的故障不会影响其他服务。增......
  • 昇思25天学习打卡营第16天|ShuffleNet图像分类
    ShuffleNet网络介绍        ShuffleNetV1是由旷视科技提出的一种高效计算的卷积神经网络(CNN)模型,主要用于移动设备。与MobileNet和SqueezeNet类似,ShuffleNetV1的设计目标是利用有限的计算资源达到最佳模型精度。其核心设计是引入了PointwiseGroupConvolution和Channe......
  • HTTP Message Handlers in ASP.NET Web API
    HTTPMessageHandlersinASP.NETWebAPIArticle05/12/20229contributorsFeedbackInthisarticleServer-SideMessageHandlersCustomMessageHandlersAddingaHandlertothePipelineExample:X-HTTP-Method-OverrideShow3moreA messagehandler ......