无法在 NLog 中设置我的连接字符串

2024-03-11

NLog.config 文件不设置连接字符串。

<?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">

  <!-- Load the ASP.NET Core plugin -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore" />
  </extensions>
  <variable name="SirNLogDb" value="data source=SQL_MULALLEY;initial catalog=LogFiles;User ID=xxx;Password=yyy;">
  </variable>
  <!--  providerName="System.Data.SqlClient"-->

  <!-- the targets to write to -->
  <targets>
    <target name="db"
            xsi:type="Database"
            dbProvider="System.Data.SqlClient"
            connectionString="${var:SirNLogDb}"
            commandType="StoredProcedure"
            commandText="[dbo].[NLog_AddEntry_p]">
      <parameter name="@machineName"    layout="${machinename}" />
      <parameter name="@siteName"       layout="${iis-site-name}" />
      <parameter name="@logged"         layout="${date}" />
      <parameter name="@level"          layout="${level}" />
      <parameter name="@username"       layout="${aspnet-user-identity}" />
      <parameter name="@message"        layout="${message}" />
      <parameter name="@logger"         layout="${logger}" />
      <parameter name="@properties"     layout="${all-event-properties:separator=|}" />
      <parameter name="@serverName"     layout="${aspnet-request:serverVariable=SERVER_NAME}" />
      <parameter name="@port"           layout="${aspnet-request:serverVariable=SERVER_PORT}" />
      <parameter name="@url"            layout="${aspnet-request:serverVariable=HTTP_URL}" />
      <parameter name="@https"          layout="${when:inner=1:when='${aspnet-request:serverVariable=HTTPS}' == 'on'}${when:inner=0:when='${aspnet-request:serverVariable=HTTPS}' != 'on'}" />
      <parameter name="@serverAddress"  layout="${aspnet-request:serverVariable=LOCAL_ADDR}" />
      <parameter name="@remoteAddress"  layout="${aspnet-request:serverVariable=REMOTE_ADDR}:${aspnet-request:serverVariable=REMOTE_PORT}" />
      <parameter name="@callSite"       layout="${callsite}" />
      <parameter name="@exception"      layout="${exception:tostring}" />
    </target>
  </targets>

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

I put a breakpoint and the connection string is null; enter image description here

我的启动方法如下;

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvcCore()
            .AddMvcOptions(o => o.OutputFormatters.Add(
                new JsonOutputFormatter(new JsonSerializerSettings(), ArrayPool<char>.Shared)));
        var connectionStringMSurveyV2 = Configuration.GetConnectionString("MSurveyV2Db");
        services.AddScoped<MSurveyV2Db>(_ => new MSurveyV2Db(connectionStringMSurveyV2));
        var connectionStringSir = Configuration.GetConnectionString("SirDb");
        services.AddScoped<SirDb>(_ => new SirDb(connectionStringSir));
        services.AddScoped<IPropertiesRepo, PropertiesRepo>();
        services.AddScoped<ISirUoW, SirUoW>();
        services.AddScoped<Services.IMailService, Services.MailService>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();
        loggerFactory.AddDebug();
        loggerFactory.AddNLog();
        //add NLog.Web
        app.AddNLogWeb();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler();
        }

        app.UseMvc();
        AutoMapper.Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<Exception, OperationStatus>();
            cfg.CreateMap<ViewSelectedContracts, ContractDto>();
        });
        var logger = LogManager.GetCurrentClassLogger();
        logger.Info("Logged in");
    }
}

编辑 - 我将记录器规则更改为<logger name="*" minlevel="Trace" writeTo="db" />但它仍然没有输出任何内容。但是我查找了 c:\temp\internal-nlog.txt 并且它尚未创建。所以看来 nlog.config 文件被忽略了。但它在我的项目中 Startup.cs 文件旁边。

EDIT2: - 可以通过将“复制到输出目录”设置为“始终复制”来解决空配置。 从下面的评论来看,我现在已经开始工作了。


更新答案

从 NLog.Web.AspNetCore 4.8(.NET Core 控制台程序的 NLog.Extensions.Logging 1.4)开始,您可以直接从 appSettings.json 读取

${configsetting:name=MyConnectionString}

see docs https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer


原答案

不幸的是,.NET Core 的 NLog 尚不支持从 appSettings.json / app.config 读取连接字符串/设置。

两种选择:

  1. 使用变量以编程方式设置连接字符串。 在你的 nlog.config 中:

    <target ... connectionString="${var:myConnectionstring}"  ... />
    

    并在代码中:(例如在Configure)

    LogManager.Configuration.Variables["myConnectionstring"] = "...."; //read config here
    
  2. 或者,在 nlog.config 中设置连接字符串。

    在你的 nlog.config 中:

    <variable name="myConnectionstring" value="...." />  
    

    并在 nlog.config 中的目标中使用:

    <target ... connectionString="${var:myConnectionstring}" ... />
    
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法在 NLog 中设置我的连接字符串 的相关文章

  • 为什么存在 async 关键字

    浏览 msdn 9 频道视频时 我发现以下未答复的评论 希望有人能解释一下 我不明白 async 关键字的意义 为什么不直接允许 任何时候方法返回任务时都会使用await关键字 就像迭代器一样 可以在任何返回 IEnumerable 的方法
  • 具有不同大小结构的结构数组的 malloc()

    如果每个结构都包含一个大小不同的字符串数组 那么如何正确地 malloc 一个结构数组 因此每个结构可能有不同的大小 并且不可能 realloc 结构体数量 sizeof 结构体名称 after malloc 初始大小 sizeof 结构名
  • 将字节数组转换为托管结构

    更新 这个问题的答案帮助我编写了开源项目GitHub 上的 AlicanC 现代战争 2 工具 https github com AlicanC AlicanC s Modern Warfare 2 Tool 你可以看到我是如何阅读这些数据
  • System.IO.IOException:由于意外>数据包格式,握手失败?

    有谁知道这意味着什么 System Net WebException 底层连接已关闭 发送时发生意外错误 gt System IO IOException 由于意外 握手失败 数据包格式 在 System Net Security SslS
  • ASP.NET Core 与现有的 IoC 容器和环境?

    我想运行ASP NET 核心网络堆栈以及MVC在已托管现有应用程序的 Windows 服务环境中 以便为其提供前端 该应用程序使用 Autofac 来处理 DI 问题 这很好 因为它已经有一个扩展Microsoft Extensions D
  • 为什么Apache MPM prefork.c 使用互斥体来保护accept()?

    我坐下来读书Apache 的 MPM prefork c http code metager de source xref apache httpd server mpm prefork prefork c这段代码使用了一个名为accept
  • 如何创建用于 QML 的通用对象模型?

    我想知道是否有任何宏或方法如何将 Qt 模型注册为 QObject 的属性 例如 我有AnimalModel http doc qt io qt 5 qtquick modelviewsdata cppmodels html qabstra
  • 如何使用MySqlCommand和prepare语句进行多行插入?(#C)

    Mysql 给出了如何使用准备语句和 NET 插入行的示例 http dev mysql com doc refman 5 5 en connector net programming prepared html http dev mysq
  • 将字符串转换为正确的 URI 格式?

    有没有简单的方法可以将电子邮件地址字符串转换为正确的 URI 格式 Input http mywebsite com validate email 3DE4ED727750215D957F8A1E4B117C38E7250C33 email
  • 对 boost 库的依赖项没有完整路径

    我已经成功构建了动态库 依赖于使用自定义前缀构建和安装的 boost 库 b2 install prefix PREFIX 然而 当我跑步时otool L在我的库中 我得到如下输出 libboost regex dylib compatib
  • TcpClient 在异步读取期间断开连接

    我有几个关于完成 tcp 连接的问题 客户端使用 Tcp 连接到我的服务器 在接受客户端后listener BeginAcceptTcpClient ConnectionEstabilishedCallback null 我开始阅读netw
  • 如何在 C++ 中将 CString 转换为 double?

    我如何转换CString to a double在 C 中 Unicode 支持也很好 Thanks A CString可以转换为LPCTSTR 这基本上是一个const char const wchar t 在 Unicode 版本中 知
  • libxml2 xmlChar * 到 std::wstring

    libxml2似乎将所有字符串存储在 UTF 8 中 如xmlChar xmlChar This is a basic byte in an UTF 8 encoded string It s unsigned allowing to pi
  • 使用 WF 的多线程应用程序的错误处理模式?

    我正在写一个又长又详细的问题 但只是放弃了它 转而选择一个更简单的问题 但我在这里找不到答案 应用程序简要说明 我有一个 WPF 应用程序 它生成多个线程 每个线程执行自己的 WF 处理线程和 WF 中的错误 允许用户从 GUI 端进行交互
  • 为什么要在 C++ 中使用 typedef?

    可以说我有 set
  • 0-1背包算法

    以下 0 1 背包问题是否可解 浮动 正值和 浮动 权重 可以是正数或负数 背包的 浮动 容量 gt 0 我平均有 这是一个相对简单的二进制程序 我建议用蛮力进行修剪 如果任何时候你超过了允许的重量 你不需要尝试其他物品的组合 你可以丢弃整
  • 使用 HTMLAgilityPack 从节点的子节点中选择所有

    我有以下代码用于获取 html 页面 将网址设置为绝对 然后将链接设置为 rel nofollow 并在新窗口 选项卡中打开 我的问题是关于将属性添加到 a s string url http www mysite com string s
  • C 中带有指针的结构的内存开销[重复]

    这个问题在这里已经有答案了 我意识到当我的结构包含指针时 它们会产生内存开销 这里有一个例子 typedef struct int num1 int num2 myStruct1 typedef struct int p int num2
  • 如何引用解决方案之外的项目?

    我有一个 Visual Studio C 解决方案 其中包含一些项目 其中一个项目需要引用另一个不属于解决方案的项目 一开始我引用了dll
  • 为什么 Linux 对目录使用 getdents() 而不是 read()?

    我浏览 K R C 时注意到 为了读取目录中的条目 他们使用了 while read dp gt fd char dirbuf sizeof dirbuf sizeof dirbuf code Where dirbuf是系统特定的目录结构

随机推荐