LoginSignup
2
2

More than 5 years have passed since last update.

NLogからFluentdのノードへログを送る方法

Last updated at Posted at 2017-03-09

Windowsのログの集約で困っておりまして、NLogを用いてFluentdのノードへ送ることが出来たので
そのメモ書きです

NuGetで下記の2つをインストールします

NLog: https://www.nuget.org/packages/NLog
NLog.Targets.Fluentd: https://www.nuget.org/packages/NLog.Targets.Fluentd/

Fluentdのノードへログを送るための設定は、 NLog.configからは指定できないっぽいので、
プログラマブルに指定する必要があります

public class Configurator
{
    // Fluentdの設定を返します
    static NLog.Targets.Target GetFluentdTarget()
    {
        var target = new NLog.Targets.Fluentd();
        target.Layout = new NLog.Layouts.SimpleLayout("${message}");
        target.Host = "127.0.0.1"; // TODO:環境に合わせる必要あり
        target.Port = 24224; // TODO:環境に合わせる必要あり
        target.Tag = "tag.tag"; // TODO:環境に合わせる必要あり
        target.NoDelay = true;
        target.LingerEnabled = false;
        target.LingerTime = 2;
        target.EmitStackTraceWhenAvailable = false;
        return WrapTarget(target);
    }

    // Fluentdの設定だけだと同期的にログを送信してしまうので非同期&リトライの設定を行います
    static NLog.Targets.Target WrapTarget(NLog.Targets.Target target)
    {
        var retryWrapper = new NLog.Targets.Wrappers.RetryingTargetWrapper("RetryingWrapper", target, 3, 1000);
        var asyncWrapper = new NLog.Targets.Wrappers.AsyncTargetWrapper("AsyncWrapper", retryWrapper);
        return asyncWrapper;
    }

    public static NLog.Config.LoggingConfiguration GetConfig()
    {
        var config = new NLog.Config.LoggingConfiguration();
        var target = GetFluentdTarget();
        config.AddTarget("fluentd", target);
        config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Debug, target));
        return config;
    }
}

// Global.asax.cs(アプリケーションの初期化時に設定します)
public class Global : HttpApplication
{
    protected void Application_Start()
    {
        // Fluentdの設定を行ったConfigを設定する
        LogManager.Configuration = LogConfigurator.GetConfig();
    }
}

今回はこの方法で設定しましたが、ロガーをWrapしたりする方法も良さそうな気がします

2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2