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

如何配置NLog向不同结构的多张日志表写入不同数据?

Using NLog to Log to Multiple Tables with Different Schemas

Absolutely! NLog is fully equipped to handle logging to multiple distinct tables—even when their structures are totally different. Here’s a practical, step-by-step approach to set this up for your two tables:

1. Set Up Separate Database Targets

First, you’ll define a unique <target> in your NLog configuration for each log table. Each target will specify the connection string, the SQL insert command tailored to the table’s schema, and map NLog properties to your table columns.

Let’s say you have two tables:

  • ErrorLogs: Columns Id (auto-increment), Message, ExceptionDetails, CreatedTimestamp
  • UserActivityLogs: Columns Id (auto-increment), UserId, ActionTaken, IpAddress, CreatedTimestamp

Your NLog.config would include targets like this:

<targets>
  <!-- Target for error logs -->
  <target xsi:type="Database" 
          name="ErrorLogTable" 
          connectionString="YourDatabaseConnectionString">
    <commandText>
      INSERT INTO ErrorLogs (Message, ExceptionDetails, CreatedTimestamp)
      VALUES (@message, @exception, @timestamp);
    </commandText>
    <parameter name="@message" layout="${message}" />
    <parameter name="@exception" layout="${exception:format=ToString}" />
    <parameter name="@timestamp" layout="${date:format=yyyy-MM-dd HH:mm:ss.fff}" />
  </target>

  <!-- Target for user activity logs -->
  <target xsi:type="Database" 
          name="UserActivityLogTable" 
          connectionString="YourDatabaseConnectionString">
    <commandText>
      INSERT INTO UserActivityLogs (UserId, ActionTaken, IpAddress, CreatedTimestamp)
      VALUES (@userId, @action, @ip, @timestamp);
    </commandText>
    <parameter name="@userId" layout="${event-properties:Item=UserId}" />
    <parameter name="@action" layout="${event-properties:Item=ActionTaken}" />
    <parameter name="@ip" layout="${event-properties:Item=IpAddress}" />
    <parameter name="@timestamp" layout="${date:format=yyyy-MM-dd HH:mm:ss.fff}" />
  </target>
</targets>

2. Configure Logging Rules to Route Logs

Next, set up rules to direct specific logs to their respective targets. You can do this in a few flexible ways:

Option A: Use Dedicated Logger Names

Create named loggers in your code (e.g., "ErrorLogger" and "UserActivityLogger") and route them to the right targets:

<rules>
  <!-- Send logs from "ErrorLogger" to ErrorLogTable -->
  <logger name="ErrorLogger" minlevel="Error" writeTo="ErrorLogTable" />
  
  <!-- Send logs from "UserActivityLogger" to UserActivityLogTable -->
  <logger name="UserActivityLogger" minlevel="Info" writeTo="UserActivityLogTable" />
</rules>

Option B: Use Log Levels or Custom Tags

If you prefer, route based on log levels (e.g., all Errors go to the error table) or add custom properties to tag logs and filter them:

<rules>
  <logger minlevel="Error" writeTo="ErrorLogTable" />
  <logger minlevel="Info" writeTo="UserActivityLogTable" filter="equals('${event-properties:Item=LogType}', 'UserActivity')" />
</rules>

3. Log Data with Custom Properties

In your code, use NLog’s fluent API to attach custom properties that map directly to your table columns. Here’s how it works for both scenarios:

For Error Logs

// Get the dedicated error logger
var errorLogger = NLog.LogManager.GetLogger("ErrorLogger");

try
{
  // Your business logic here
}
catch (Exception ex)
{
  errorLogger.Error(ex, "Failed to process customer order");
}

For User Activity Logs

// Get the dedicated activity logger
var activityLogger = NLog.LogManager.GetLogger("UserActivityLogger");

// Attach custom properties matching your table columns
activityLogger.WithProperty("UserId", currentUser.Id)
              .WithProperty("ActionTaken", "PasswordChanged")
              .WithProperty("IpAddress", userIpAddress)
              .Info("User updated their account password");

Key Notes

  • Don’t forget to install the NLog.Database NuGet package—it’s required for database targets to work.
  • If you’re using .NET Core/.NET 5+, you can integrate NLog with the built-in logging system via dependency injection. Just register your loggers as usual, and the routing rules will still apply seamlessly.
  • This pattern scales easily: add more targets and rules if you need to log to additional tables later.

This setup ensures your distinct log data flows to the correct tables with their respective schemas, no messy custom code required!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:34:53