我想用我的错误消息保存一些附加信息。例如,它应该是用户查询,或其他。我该怎么办?
是否有任何构建方法来记录集合,结构或对象?或者我应该自己序列化?
答案 0 :(得分:20)
不,没有内置的序列化对象。当您在内部使用Debug<T>(string message, T argument)
等格式化方法时(可以看到类NLog.LogEventInfo
),简单String.Format
用于创建格式化消息(即在每个参数上调用ToString()
)。
我使用Json.NET将对象和集合序列化为JSON。创建像
这样的扩展方法很容易public static string ToJson(this object value)
{
var settings = new JsonSerializerSettings {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
return JsonConvert.SerializeObject(value, Formatting.Indented, settings);
}
然后在记录期间使用它:
Logger.Debug("Saving person {0}", person.ToJson());
答案 1 :(得分:5)
/**
* class used to optimize loggers
*
* Logger.Trace("info "+bigData.ToString());
* Logger.Trace("info {0}",bigData.ToString());
* both creates and parses bigData even if Trace is disabled
*
* Logger.Trace("info {0}", LazyJsonizer.Create(bigData));
* Logger.Trace(LazyJsonizer.Instance, "info {0}", bigData);
* creates string only if Trace is enabled
*
* http://stackoverflow.com/questions/23007377/nlog-serialize-objects-or-collections-to-log
*/
public class LazyJsonizer<T>
{
T Value;
public LazyJsonizer(T value)
{
Value = value;
}
override public string ToString()
{
return LazyJsonizer.Instance.Format(null, Value, null);
}
}
public class LazyJsonizer : IFormatProvider, ICustomFormatter
{
static public readonly LazyJsonizer Instance = new LazyJsonizer();
static public LazyJsonizer<T> Create<T>(T value)
{
return new LazyJsonizer<T>(value);
}
public object GetFormat(Type formatType)
{
return this;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
try
{
return JsonConvert.SerializeObject(arg);
}
catch (Exception ex)
{
return ex.Message;
}
}
}
答案 2 :(得分:3)
这个简化的例子展示了我在玩NLog后所得到的。 在我的解决方案中,我使用基于代码的配置来减轻每个asp.net项目的重复xml nlog.config文件。适用于NLog v4.4.1。
Logger static helper:
private static readonly Logger DefaultLogger = LogManager.GetLogger("Application");
public static void Debug(Exception exception = null, string message = null, object data = null)
=> Write(DefaultLogger, LogLevel.Debug, message, exception, data);
private static void Write(
Logger logger,
LogLevel level,
string message = null,
Exception exception = null,
object data = null)
{
var eventInfo = new LogEventInfo()
{
Level = level,
Message = message,
Exception = exception,
Parameters = new[] { data, tag }
};
if (data != null) eventInfo.Properties["data"] = data.ToJson();
eventInfo.Properties["level"] = eventInfo.GetLevelCode(); // custom level to int conversion
logger.Log(eventInfo);
}
FileTarget配置:
var jsonFileTarget = new FileTarget()
{
Name = "file_json",
Layout = new JsonLayout()
{
Attributes =
{
new JsonAttribute("level", "${event-context:item=level}"),
new JsonAttribute("time", "${longdate}"),
new JsonAttribute("msg", "${message}"),
new JsonAttribute("error", "${exception:format=tostring}"),
new JsonAttribute("data", "${event-context:item=data}", false),
},
RenderEmptyObject = false,
},
FileName = $"{LogFile.Directory}/json_{LogFile.Suffix}", // use settings from static LogFile class
ArchiveFileName = $"{LogFile.Directory}/json_{LogFile.ArchiveSuffix}",
ArchiveAboveSize = LogFile.MaxSize
};
自定义对象的输出:
{ "level": "10", "time": "2017-02-02 16:24:52.3078", "data":{"method":"get","url":"http://localhost:44311/"}}
答案 3 :(得分:0)
NLog版本。 4.5包括用于结构化日志记录的新功能:
logger.Debug("{shopitem} added to basket by {user}", new { Id=6, Name = "Jacket", Color = "Orange" }, "Kenny");
https://github.com/NLog/NLog/wiki/How-to-use-structured-logging
答案 4 :(得分:0)
有一个非常简单的解决方案,可以使用nlog实现结构日志记录。
try
{
// bla bla bla
}
catch (Exception ex)
{
_logger.LogError(ex, "MyRequest{@0}", request);
}
符号@序列化请求对象
https://github.com/NLog/NLog/wiki/How-to-use-structured-logging