示例#1
0
        public override void Log(NpgsqlLogLevel level, int connectorId, string msg, Exception exception = null)
        {
            _logger.Write((Serilog.Events.LogEventLevel)level, msg);

            if (msg.StartsWith("Query duration"))
            {
                string digits = new String(msg.Where(Char.IsDigit).ToArray());
                int    ms     = Convert.ToInt32(digits);
                if (ms > highest_ms)
                {
                    highest_ms = ms;
                    _logger.Information("Query duration high water mark is now " + digits);
                }
            }
        }
示例#2
0
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="level">日志等级</param>
        /// <param name="content">日志内容</param>
        public void WriteLog(LogLevel level, ILogContent content)
        {
            var provider      = GetFormatProvider();
            var logEventLevel = ConvertTo(level);

            if (logEventLevel == null)
            {
                return;
            }
            if (provider == null)
            {
                throw new NullReferenceException("日志格式化提供程序不可为空");
            }
            var message = provider.Format("", content, null);

            _logger.Write(logEventLevel.SafeValue(), message);
        }
示例#3
0
            public bool WriteCore(TraceEventType eventType, int eventId, object state, Exception exception, Func <object, Exception, string> formatter)
            {
                var level = _getLogEventLevel(eventType);

                // According to docs http://katanaproject.codeplex.com/SourceControl/latest#src/Microsoft.Owin/Logging/ILogger.cs
                // "To check IsEnabled call WriteCore with only TraceEventType and check the return value, no event will be written."
                if (state == null)
                {
                    return(_logger.IsEnabled(level));
                }
                if (!_logger.IsEnabled(level))
                {
                    return(false);
                }
                _logger.Write(level, exception, formatter(state, exception));
                return(true);
            }
示例#4
0
            public bool WriteCore(TraceEventType eventType, int eventId, object state, Exception exception, Func <object, Exception, string> formatter)
            {
                var level = _getLogEventLevel(eventType);

                if (state == null)
                {
                    return(_logger.IsEnabled(level));
                }

                if (!_logger.IsEnabled(level))
                {
                    return(false);
                }

                _logger.Write(level, exception, formatter(state, exception));

                return(true);
            }
示例#5
0
        public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
        {
            if (logLevel == LogLevel.None)
            {
                return;
            }

            Serilog.Events.LogEventLevel logEventLevel = Serilog.Events.LogEventLevel.Information;
            switch (logLevel)
            {
            case LogLevel.Information:
                logEventLevel = Serilog.Events.LogEventLevel.Information;
                break;

            case LogLevel.Error:
                logEventLevel = Serilog.Events.LogEventLevel.Error;
                break;

            case LogLevel.Warning:
                logEventLevel = Serilog.Events.LogEventLevel.Warning;
                break;

            case LogLevel.Critical:
                logEventLevel = Serilog.Events.LogEventLevel.Fatal;
                break;

            case LogLevel.Debug:
                logEventLevel = Serilog.Events.LogEventLevel.Debug;
                break;

            case LogLevel.Trace:
                logEventLevel = Serilog.Events.LogEventLevel.Verbose;
                break;
            }

            _logger.Write(logEventLevel, exception, formatter.Invoke(state, exception));
        }
示例#6
0
        private void LogHttpRequest(HttpContext context, DiagnosticContextCollector collector, string requestBody, string finalResponseBody, int finalStatusCode, Stopwatch stopWatch,
                                    bool isRequestOk,
                                    Exception ex)
        {
            stopWatch.Stop();
            var endpoint             = context.GetEndpoint();
            var shouldLogHttpRequest = !(endpoint?.Metadata?.GetMetadata <IgnoreLogAttribute>() is object);

            if (!shouldLogHttpRequest)
            {
                return;
            }

            if (_options.EnableResponseLogging || (!isRequestOk && _options.EnableExceptionLogging))
            {
                bool         shouldLogRequestData = ShouldLogRequestData(context);
                JsonDocument requestBodyObject    = null;
                if ((shouldLogRequestData || (!isRequestOk && _options.LogResponseDataOnException)) &&
                    !string.IsNullOrWhiteSpace(requestBody))
                {
                    try { requestBody = requestBody.MaskFields(_options.MaskedProperties.ToArray(), _options.MaskFormat); } catch (Exception) { }
                    if (requestBody.Length > _options.RequestBodyTextLengthLogLimit)
                    {
                        requestBody = requestBody.Substring(0, _options.RequestBodyTextLengthLogLimit);
                    }
                    else
                    {
                        try { requestBodyObject = System.Text.Json.JsonDocument.Parse(requestBody); } catch (Exception) { }
                    }
                }
                else
                {
                    requestBody = null;
                }

                var requestHeader = new Dictionary <string, object>();
                if (_options.ShouldLogRequestHeader ||
                    (!isRequestOk && _options.LogRequestHeaderOnException))
                {
                    try
                    {
                        var valuesByKey = context.Request.Headers.Mask(_options.MaskedProperties.ToArray(), _options.MaskFormat).GroupBy(x => x.Key);
                        foreach (var item in valuesByKey)
                        {
                            if (item.Count() > 1)
                            {
                                requestHeader.Add(item.Key, item.Select(x => x.Value.ToString()).ToArray());
                            }
                            else
                            {
                                requestHeader.Add(item.Key, item.First().Value.ToString());
                            }
                        }
                    }
                    catch (Exception)
                    {
                        SelfLog.WriteLine("Cannot parse response header");
                    }
                }

                var userAgentDic = new Dictionary <string, string>();
                if (context.Request.Headers.ContainsKey("User-Agent"))
                {
                    var userAgent = context.Request.Headers["User-Agent"].ToString();
                    userAgentDic.Add("_Raw", userAgent);
                    try
                    {
                        var uaParser   = UAParser.Parser.GetDefault();
                        var clientInfo = uaParser.Parse(userAgent);
                        userAgentDic.Add("Browser", clientInfo.UA.Family);
                        userAgentDic.Add("BrowserVersion", clientInfo.UA.Major + "." + clientInfo.UA.Minor);
                        userAgentDic.Add("OperatingSystem", clientInfo.OS.Family);
                        userAgentDic.Add("OperatingSystemVersion", clientInfo.OS.Major + "." + clientInfo.OS.Minor);
                        userAgentDic.Add("Device", clientInfo.Device.Family);
                        userAgentDic.Add("DeviceModel", clientInfo.Device.Model);
                        userAgentDic.Add("DeviceManufacturer", clientInfo.Device.Brand);
                    }
                    catch (Exception)
                    {
                        SelfLog.WriteLine("Cannot parse user agent:" + userAgent);
                    }
                }

                var requestQuery = new Dictionary <string, object>();
                try
                {
                    var valuesByKey = context.Request.Query.GroupBy(x => x.Key);
                    foreach (var item in valuesByKey)
                    {
                        if (item.Count() > 1)
                        {
                            requestQuery.Add(item.Key, item.Select(x => x.Value.ToString()).ToArray());
                        }
                        else
                        {
                            requestQuery.Add(item.Key, item.First().Value.ToString());
                        }
                    }
                }
                catch (Exception)
                {
                    SelfLog.WriteLine("Cannot parse query string");
                }

                var requestData = new
                {
                    ClientIp    = context.Connection.RemoteIpAddress.ToString(),
                    Method      = context.Request.Method,
                    Scheme      = context.Request.Scheme,
                    Host        = context.Request.Host.Value,
                    Path        = context.Request.Path.Value,
                    QueryString = context.Request.QueryString.Value,
                    Query       = requestQuery,
                    BodyString  = requestBody ?? string.Empty,
                    Body        = requestBodyObject,
                    Header      = requestHeader,
                    UserAgent   = userAgentDic,
                };

                bool   shouldLogResponseData = ShouldLogResponseData(context);
                object responseBodyObject    = null;
                if ((shouldLogResponseData || (!isRequestOk && _options.LogResponseDataOnException)))
                {
                    try { finalResponseBody = finalResponseBody.MaskFields(_options.MaskedProperties.ToArray(), _options.MaskFormat); } catch (Exception) { }

                    if (finalResponseBody != null)
                    {
                        if (finalResponseBody.Length > _options.ResponseBodyTextLengthLogLimit)
                        {
                            finalResponseBody = finalResponseBody.Substring(0, _options.ResponseBodyTextLengthLogLimit);
                        }
                        else
                        {
                            try { responseBodyObject = System.Text.Json.JsonDocument.Parse(finalResponseBody); } catch (Exception) { }
                        }
                    }
                }
                else
                {
                    finalResponseBody = null;
                }

                var responseHeader = new Dictionary <string, object>();
                if (_options.ShouldLogResponseHeader ||
                    (!isRequestOk && _options.LogResponseHeaderOnException))
                {
                    try
                    {
                        var valuesByKey = context.Response.Headers.Mask(_options.MaskedProperties.ToArray(), _options.MaskFormat).GroupBy(x => x.Key);
                        foreach (var item in valuesByKey)
                        {
                            if (item.Count() > 1)
                            {
                                responseHeader.Add(item.Key, item.Select(x => x.Value.ToString()).ToArray());
                            }
                            else
                            {
                                responseHeader.Add(item.Key, item.First().Value.ToString());
                            }
                        }
                    }
                    catch (Exception)
                    {
                        SelfLog.WriteLine("Cannot parse response header");
                    }
                }

                var responseData = new
                {
                    StatusCode = finalStatusCode,
                    stopWatch.ElapsedMilliseconds,
                    BodyString = finalResponseBody ?? string.Empty,
                    Body       = responseBodyObject,
                    Header     = responseHeader
                };

                var level = LogEventLevel.Information;
                if (finalStatusCode >= 500)
                {
                    level = LogEventLevel.Error;
                }
                else if (finalStatusCode >= 400)
                {
                    level = LogEventLevel.Warning;
                }

                var props = endpoint?.Metadata?.GetOrderedMetadata <LogCustomPropertyAttribute>()?
                            .ToDictionary(x => x.Name, x => x.Value);

                if (!collector.TryComplete(out var collectedProperties))
                {
                    collectedProperties = NoProperties;
                }
                _logger.Write(level, ex, DefaultRequestCompletionMessageTemplate, new
                {
                    Request    = requestData,
                    Response   = responseData,
                    Properties = props,
                    Context    = collectedProperties.ToDictionary(x => x.Name, x => x.Value.ToString()),
                });
            }
        }
示例#7
0
        protected internal void FormatCallerMessage(LogEventLevel level, string memberName, string sourceFilePath, int sourceLineNumber)
        {
            const string callerMessageFormat = "File: {SourceFileName} \t Method:{MethodName} \t Line Number {SourceLineNumber}";
            var          fileName            = Path.GetFileName(sourceFilePath);

            log.Write(level, callerMessageFormat, fileName, memberName, sourceLineNumber);
        }
 /// <summary>
 /// Logging message from SDK
 /// </summary>
 /// <param name="messageToWrite"></param>
 public void Log(string messageToWrite)
 {
     logger.Write(LogEventLevel.Verbose, messageToWrite);
 }
示例#9
0
文件: Logger.cs 项目: amersaw/tlogger
 public void Write(LogEventLevel information, string v, LogEntry entry)
 {
     _logger.Write(information, v, entry);
 }
示例#10
0
 public static void WriteUsageLog(LogDetail logDetail)
 {
     _usageLogger.Write(LogEventLevel.Information, "{@LogDetail}", logDetail);
 }
示例#11
0
 public static void WritePerformanceLog(LogDetail logDetail)
 {
     _performanceLogger.Write(LogEventLevel.Information, "{@LogDetail}", logDetail);
 }
 public void Write(LogEvent logEvent)
 {
     _logger.Write(logEvent);
     Console.WriteLine("Hey from logger");
 }
示例#13
0
 public static void Message_Debug(string msg)
 {
     log.Write(LogEventLevel.Debug, msg);
 }