前端时间写了个随笔 log4net.NoSql 的代码。

redis的C#客户端使用了 ServiceStackRedis,json序列化使用 RestSharp。代码结构如下:

log4net.redis+logstash+kibana+elasticsearch+redis 实现日志系统

 

JsonLayout.cs代码:

  public class JsonLayout : LayoutSkeleton
    {
        public readonly string HostName;
        private readonly ITextTransform _transform;

        public string LogType { get; set; }
        public string AppName { get; set; }

        public JsonLayout()
            : base()
        {
            HostName = Dns.GetHostName();
            _transform = TextTransform.Instance;
        }

        public override string ContentType
        {
            get { return "application/json"; }
        }

        public override void ActivateOptions()
        {
            //nothing to do here
        }

        public override void Format(TextWriter writer, LoggingEvent loggingEvent)
        {
            var info = loggingEvent.LocationInformation;
            var loggingEventJson = _transform.Serialize(new JsonLogMessage
                {
                    class_method = info.MethodName,
                    class_name = info.ClassName,
                    host_ip = HostName,
                    line_number = info.LineNumber,
                    log_level = loggingEvent.Level.DisplayName,
                    log_message = loggingEvent.MessageObject.ToString(),
                    exception = BuildExceptionMessage(loggingEvent),
                    log_time = loggingEvent.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss"),
                    logger_name = loggingEvent.LoggerName,
                    run_time = "0", //目前获取不到
                    thread_name = loggingEvent.ThreadName,
                    host = HostName,
                    log_type = this.LogType,
                    app_name = this.AppName,
                    path = ""
                });

            writer.Write(loggingEventJson);
        }

        private JsonLogException BuildExceptionMessage(LoggingEvent loggingEvent)
        {
            if (loggingEvent.ExceptionObject == null)
                return new JsonLogException { exception_class = "", exception_message = "", exception_stacktrace = "" };

            var exception = loggingEvent.ExceptionObject;
            return
                new JsonLogException
                {
                    exception_class = exception.Source,
                    exception_message = exception.Message,
                    exception_stacktrace = exception.StackTrace
                };
        }
    }
View Code

相关文章: