using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NLog
{
static public class CanNLogHelper
{
static Dictionary<string, Config.LoggingConfiguration> kvLoger = new Dictionary<string, Config.LoggingConfiguration>();
//static public void InitCanDevLogListener(int num)
//{
// for (int i = 0; i < num; i++)
// {
// string canDev = $"0{i}5";
// if (!kvLoger.ContainsKey(canDev))
// {
// kvLoger.Add(canDev, LogConfig(canDev));
// }
// }
//}
static public void AddCanDevLogListener(List<string> name)
{
foreach (var item in name)
{
if (!kvLoger.ContainsKey(item))
{
kvLoger.Add(item, LogConfig(item));
}
}
}
static public Logger GetCanLogger(string name)
{
if(!kvLoger.ContainsKey(name))
{
kvLoger.Add(name, LogConfig(name));
}
LogManager.Configuration = kvLoger[name];
return LogManager.GetLogger(name);
}
static public void SetBoardCastLog(string info)
{
foreach (KeyValuePair<string, Config.LoggingConfiguration> item in kvLoger)
{
GetCanLogger(item.Key).Info(info);
}
}
static public Config.LoggingConfiguration LogConfig(string name)
{
//创建一个配置文件对象
Config.LoggingConfiguration config = new Config.LoggingConfiguration();
//创建目标
Targets.FileTarget target = new Targets.FileTarget() { FileName = $"logs/CanLog/{name}.log", Layout = "${longdate} ${uppercase:${level}} ${message}" };
//添加日志路由规则
config.AddRule(LogLevel.Trace, LogLevel.Off, target);
return config;
}
}
}
调用案例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NLog
{
//Install-Package NLog -Version 4.5.11
internal class Program
{
static void Main(string[] args)
{
// CanNLogHelper.InitCanDevLogListener(20);
Dictionary<string, string> dic = new Dictionary<string, string>()
{
{"01","111" },
{"02","222" },
{"03","333" },
{"04","444" },
};
CanNLogHelper.AddCanDevLogListener(new List<string> { dic["01"], dic["02"], dic["03"], dic["04"] });
CanNLogHelper.SetBoardCastLog("999");
CanNLogHelper.GetCanLogger(dic["01"]).Info("111");
CanNLogHelper.GetCanLogger(dic["03"]).Info("aaa");
CanNLogHelper.GetCanLogger(dic["02"]).Info("111");
CanNLogHelper.GetCanLogger(dic["04"]).Info("111");
CanNLogHelper.GetCanLogger(dic["03"]).Info("333");
CanNLogHelper.GetCanLogger(dic["02"]).Info("333");
CanNLogHelper.SetBoardCastLog("888");
}
}
}
配置文件笔记
滚动日志策略