You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET 6 Azure Functions V4中结合依赖注入使用NLog

Azure Functions V4 集成 NLog 实现数据库与本地文件日志

前置依赖安装

先安装以下NuGet包:

  • NLog.Web.AspNetCore(核心集成包)
  • NLog.Database(用于数据库日志写入)
  • Microsoft.Extensions.Configuration.Binder(用于读取配置)

1. Startup.cs 配置(In-Process 模型)

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using NLog;
using NLog.Web;

[assembly: FunctionsStartup(typeof(YourFunctionApp.Startup))]
namespace YourFunctionApp
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            // 加载应用配置
            var configuration = builder.GetContext().Configuration;

            // 初始化NLog
            LogManager.Setup()
                .LoadConfigurationFromAppSettings()
                .LoadConfigurationFromFile("nlog.config", optional: false)
                .GetCurrentClassLogger();

            // 替换默认日志提供器为NLog
            builder.Services.AddLogging(loggingBuilder =>
            {
                loggingBuilder.ClearProviders();
                loggingBuilder.AddNLogWeb();
            });
        }
    }
}

2. 函数示例代码(AzureFunctions.cs)

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;

namespace YourFunctionApp
{
    public class SampleFunction
    {
        private readonly ILogger<SampleFunction> _logger;

        // 构造函数注入ILogger
        public SampleFunction(ILogger<SampleFunction> logger)
        {
            _logger = logger;
        }

        [FunctionName("SampleHttpFunction")]
        public IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req)
        {
            // 不同级别日志示例
            _logger.LogTrace("Trace级别日志");
            _logger.LogDebug("Debug级别日志");
            _logger.LogInformation("Information级别日志");
            _logger.LogWarning("Warning级别日志");
            _logger.LogError("Error级别日志");
            _logger.LogCritical("Critical级别日志");

            return new OkObjectResult("日志已写入");
        }
    }
}

3. appsettings.json 配置

{
  "ConnectionStrings": {
    "LogDb": "Server=你的数据库地址;Database=日志数据库名;User Id=账号;Password=密码;"
  },
  "NLog": {
    "InternalLogLevel": "Info",
    "InternalLogFile": "nlog-internal.log"
  }
}

4. 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="Info"
      internalLogFile="nlog-internal.log">

  <!-- 从appsettings读取数据库连接字符串 -->
  <variable name="LogDbConnection" value="${configsetting:name=ConnectionStrings.LogDb}" />

  <!-- 日志目标配置 -->
  <targets>
    <!-- 本地文件日志:按日期生成文件,存储到项目根目录Logs文件夹 -->
    <target xsi:type="File" 
            name="FileTarget" 
            fileName="${basedir}/Logs/${shortdate}.txt" 
            layout="${longdate} | ${level:uppercase=true} | ${logger} | ${message} ${exception:format=ToString}" />

    <!-- 数据库日志:SQL Server示例,需提前创建Logs表 -->
    <target xsi:type="Database" 
            name="DbTarget" 
            connectionString="${LogDbConnection}">
      <commandText>
        INSERT INTO Logs (LogDate, Level, Logger, Message, Exception)
        VALUES (@LogDate, @Level, @Logger, @Message, @Exception);
      </commandText>
      <parameter name="@LogDate" layout="${date:format=yyyy-MM-dd HH:mm:ss.fff}" />
      <parameter name="@Level" layout="${level}" />
      <parameter name="@Logger" layout="${logger}" />
      <parameter name="@Message" layout="${message}" />
      <parameter name="@Exception" layout="${exception:format=ToString}" />
    </target>
  </targets>

  <!-- 日志路由规则 -->
  <rules>
    <!-- 所有级别日志同时写入文件和数据库 -->
    <logger name="*" minlevel="Trace" writeTo="FileTarget,DbTarget" />
  </rules>
</nlog>

关键注意事项

  • 文件权限与路径:${basedir} 本地指向项目根目录,Azure部署后指向D:\home\site\wwwroot,需确保Logs文件夹存在且有写入权限;本地可手动创建,Azure可通过Kudu工具创建。
  • 数据库表结构:需提前创建Logs表,字段对应nlog.config中的参数(LogDate、Level、Logger、Message、Exception)。
  • nlog.config属性:在Visual Studio中,将nlog.config的「复制到输出目录」设置为「始终复制」,确保部署时能被正确加载。
  • Isolated模型适配:若使用Isolated进程模型,Startup配置需调整为ConfigureServices方法,核心初始化逻辑一致。

内容的提问来源于stack exchange,提问作者Joe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 17:12:56