示例#1
0
        /// <summary>
        /// 发送日志邮件
        /// </summary>
        /// <param name="title">邮件标题</param>
        /// <param name="content">邮件内容</param>
        /// <param name="level">日志等级</param>
        /// <param name="mandatoryMail">强制发送邮件,就算配置文件没有包含的日志等级</param>
        public void SendLogMail(string title, string content, LogEventLevel level, bool mandatoryMail = false)
        {
            var love = AppSetting.LogMailLevel.Split(",");

            if (love.Contains(level.ToString()) || (mandatoryMail && !love.Contains(level.ToString())))
            {
                Task.Run(() =>
                {
                    if (!string.IsNullOrWhiteSpace(AppSetting.LogMailFrom))
                    {
                        MailHelper.SendMail(new SendMailModel()
                        {
                            Content  = content,
                            Title    = title,
                            MailInfo = new MailEntity()
                            {
                                MailFrom = AppSetting.LogMailFrom,
                                MailHost = AppSetting.LogMailHost,
                                MailPwd  = AppSetting.LogMailPwd,
                                MailTo   = AppSetting.LogMailTo
                            }
                        });
                    }
                });
            }
        }
示例#2
0
        public Payload(string userName, LogEventLevel title, string description, string fieldName, string fieldValue)
        {
            _userName = userName;

            Color?color = title switch
            {
                LogEventLevel.Warning => Color.FromArgb(255, 101, 101),
                LogEventLevel.Error => Color.FromArgb(216, 46, 46),
                LogEventLevel.Fatal => Color.FromArgb(158, 10, 10),
                _ => null
            };

            var colorValue = color.Value.ToUint();

            if (string.IsNullOrWhiteSpace(fieldValue))
            {
                Embeds = new Embed[] { new Embed {
                                           Titel = title.ToString(), Description = description, Color = colorValue
                                       } }
            }
            ;
            else
            {
                Embeds = new Embed[] { new Embed {
                                           Titel = title.ToString(), Description = description, EmbedFields = new EmbedField[] { new EmbedField(fieldName, fieldValue) }
                                       } }
            };
        }
    }
示例#3
0
        public static string GetLevelMoniker(LogEventLevel value, string?format)
        {
            if (format == null)
            {
                return(value.ToString());
            }

            if (format.Length != 2 && format.Length != 3)
            {
                return(Casing.Format(value.ToString(), format));
            }

            // Using int.Parse() here requires allocating a string to exclude the first character prefix.
            // Junk like "wxy" will be accepted but produce benign results.
            var width = format[1] - '0';

            if (format.Length == 3)
            {
                width *= 10;
                width += format[2] - '0';
            }

            if (width < 1)
            {
                return(string.Empty);
            }

            if (width > 4)
            {
                var stringValue = value.ToString();
                if (stringValue.Length > width)
                {
                    stringValue = stringValue.Substring(0, width);
                }
                return(Casing.Format(stringValue));
            }

            var index = (int)value;

            if (index >= 0 && index <= (int)LogEventLevel.Fatal)
            {
                switch (format[0])
                {
                case 'w':
                    return(LowercaseLevelMap[index][width - 1]);

                case 'u':
                    return(UppercaseLevelMap[index][width - 1]);

                case 't':
                    return(TitleCaseLevelMap[index][width - 1]);
                }
            }

            return(Casing.Format(value.ToString(), format));
        }
示例#4
0
        /// <summary>
        /// This method will apply only upper or lower case formatting, not fixed width
        /// </summary>
        public override void Render(TextWriter output, string format = null, IFormatProvider formatProvider = null)
        {
            if (format != null && (format.Length == 2 || format.Length == 3))
            {
                // Using int.Parse() here requires allocating a string to exclude the first character prefix.
                // Junk like "wxy" will be accepted but produce benign results.
                var width = format[1] - '0';
                if (format.Length == 3)
                {
                    width *= 10;
                    width += format[2] - '0';
                }

                if (width < 1)
                {
                    return;
                }

                if (width > 4)
                {
                    var value = _value.ToString();
                    if (value.Length > width)
                    {
                        value = value.Substring(0, width);
                    }
                    output.Write(Casing.Format(value));
                    return;
                }

                var index = (int)_value;
                if (index >= 0 && index <= (int)LogEventLevel.Fatal)
                {
                    switch (format[0])
                    {
                    case 'w':
                        output.Write(_lowercaseLevelMap[index][width - 1]);
                        return;

                    case 'u':
                        output.Write(_uppercaseLevelMap[index][width - 1]);
                        return;

                    case 't':
                        output.Write(_titleCaseLevelMap[index][width - 1]);
                        return;
                    }
                }
            }

            output.Write(Casing.Format(_value.ToString(), format));
        }
示例#5
0
        static string GetLevelMoniker(LogEventLevel logEventLevel)
        {
            switch (logEventLevel)
            {
            case LogEventLevel.Verbose:
                return("Verbose");

            case LogEventLevel.Debug:
                return("Debug");

            case LogEventLevel.Information:
                return("Information");

            case LogEventLevel.Warning:
                return("Warning");

            case LogEventLevel.Error:
                return("Error");

            case LogEventLevel.Fatal:
                return("Fatal");

            default:
                return(logEventLevel.ToString());
            }
        }
示例#6
0
    public string GetLogLevel()
    {
        LogEventLevel?logLevel = Enum.GetValues(typeof(LogEventLevel)).Cast <LogEventLevel>()
                                 .Where(_serilogLog.IsEnabled).DefaultIfEmpty(LogEventLevel.Information).Min();

        return(logLevel?.ToString() ?? string.Empty);
    }
示例#7
0
        private void Log(
            string message,
            object data,
            Exception ex,
            string source,
            LogEventLevel level,
            Action <string, LogMessage> logger)
        {
            var logMessage = new LogMessage
            {
                Application   = _appName,
                Data          = data ?? RequestBody,
                Level         = level.ToString(),
                Message       = message,
                Method        = source,
                Timestamp     = DateTime.Now,
                RequestId     = RequestId.ToString(),
                CorrelationId = CorrelationId.ToString(),
                IpAddress     = IpAddress,
            };

            if (ex is not null)
            {
                logMessage.StackTrace = ex.StackTrace;
            }

            logger.Invoke("{@LogMessage}", logMessage);
        }
 private static string GetLevel(LogEventLevel level)
 {
     if (level == LogEventLevel.Information)
     {
         return("info");
     }
     return(level.ToString().ToLower());
 }
        private static void LoadLogLevel()
        {
            var configLogLevel = Environment.GetEnvironmentVariable("LOG_LEVEL") ?? _defaultLogLevel.ToString();

            bool parsed = Enum.TryParse(configLogLevel, true, out LogEventLevel logLevel);

            _loggingLevel.MinimumLevel = parsed ? logLevel : _defaultLogLevel;
        }
示例#10
0
 private static void GetExceptionData(LogEventLevel logEventLevel, Exception exception, ref LogModel logModel)
 {
     logModel.Guid      = Guid.NewGuid();
     logModel.TimeStamp = DateTime.Now;
     logModel.Level     = logEventLevel.ToString();
     logModel.Type      = exception.GetType().FullName;
     logModel.Message   = exception.InnerException != null ? exception.InnerException.Message : exception.Message;
     logModel.Exception = exception.ToString();
 }
示例#11
0
        public void Write(LogEventLevel level, string message, string sql = null, decimal?executionTime = null, long?tag = null, bool sendLogMail = true)
        {
            var model = GetLogModel(message, sql, executionTime, tag);

            Log.Logger.Write(level, "{@item} {@trackid}", model, session.TrackId);
            if (sendLogMail)
            {
                SendLogMail($"日志邮件【{level.ToString()}】", $"{JsonConvert.SerializeObject(model)} {session.TrackId}", level);
            }
        }
 public ApplicationLogMessage(IConfigurationSetting configurationSetting,
                              string requestId, string internalRequestId, string message, LogEventLevel logEventLevel, Exception exception)
 {
     _configurationSetting = configurationSetting;
     RequestId             = requestId;
     InternalRequestId     = internalRequestId;
     Message       = message;
     LogEventLevel = logEventLevel.ToString();
     Exception     = exception?.ToString();
 }
        public string GetLogFilePath(DateTime date, LogEventLevel?level, int sequenceNumber)
        {
            var tok = date.ToString(DateFormat, CultureInfo.InvariantCulture);

            if (sequenceNumber != 0)
            {
                tok += "_" + sequenceNumber.ToString("0000", CultureInfo.InvariantCulture);
            }

            return(_pathTemplate.Replace(DateSpecifier, tok).Replace(LeveSpecifier, level?.ToString().ToLower()));
        }
示例#14
0
        public LogEventAssertion WithLevel(LogEventLevel level, string because = "", params object[] becauseArgs)
        {
            Execute.Assertion
            .BecauseOf(because, becauseArgs)
            .ForCondition(Subject.Level == level)
            .FailWith("Expected message {0} to have level {1}, but it is {2}",
                      _messageTemplate,
                      level.ToString(),
                      Subject.Level.ToString());

            return(this);
        }
        private static string GetLevel(LogEventLevel level)
        {
            switch (level)
            {
            case LogEventLevel.Verbose: return("trace");

            case LogEventLevel.Information: return("info");

            case LogEventLevel.Fatal: return("critical");

            default: return(level.ToString().ToLower());
            }
        }
示例#16
0
        /// <summary>
        /// Adds the logger settings.
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <param name="initialMinimumLevel">The initial minimum level.</param>
        /// <returns>IConfigurationBuilder.</returns>
        /// <autogeneratedoc />
        public static IConfigurationBuilder AddSerilogLoggerSettings(this IConfigurationBuilder config, LogEventLevel initialMinimumLevel)
        {
            config.AddInMemoryCollection(
                new Dictionary <string, string>
            {
                ["Serilog:MinimumLevel:Default"]            = initialMinimumLevel.ToString(),
                ["Serilog:MinimumLevel:Override:Microsoft"] = "Information",
                ["Serilog:MinimumLevel:Override:System"]    = "Warning"
            }
                );

            return(config);
        }
示例#17
0
        /// <summary>
        /// Translate log level according to Digipolis logging guidelines
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        protected virtual string TranslateLevel(LogEventLevel level)
        {
            switch (level)
            {
            case LogEventLevel.Information:
                return("INFO");

            case LogEventLevel.Warning:
                return("WARN");

            default:
                return(level.ToString().ToUpper());
            }
        }
示例#18
0
        public void Start()
        {
            _pullConsoleAction.Start();
            _FetchForexTransactionsInterval.Start();
            LogEventLevel currlel = 0;

            foreach (LogEventLevel lel in Enum.GetValues(typeof(LogEventLevel)))
            {
                if (Log.IsEnabled(lel))
                {
                    currlel = lel; break;
                }
            }
            Log.Information($"Log minimum level is set to: {currlel.ToString()} ");
        }
        public void LogLevel_PropertiesContainsLevel(LogEventLevel level)
        {
            // Arrange
            var testableAppCenterSink = new TestableAppCenterSink();

            using (var logger = new LoggerConfiguration()
                                .WriteTo.Sink(testableAppCenterSink)
                                .CreateLogger())
            {
                // Act
                logger.Write(level, "test");
            }

            // Assert
            var val = Assert.Contains("level", testableAppCenterSink.LastAnalyticsProperties);

            Assert.Equal(level.ToString(), val);
        }
示例#20
0
        public static string GetLevelMoniker(LogEventLevel value, string format = null)
        {
            var index = (int)value;

            if (index < 0 || index > (int)LogEventLevel.Fatal)
            {
                return(Casing.Format(value.ToString(), format));
            }

            if (format == null || format.Length != 2 && format.Length != 3)
            {
                return(Casing.Format(GetLevelMoniker(_titleCaseLevelMap, index), format));
            }

            // Using int.Parse() here requires allocating a string to exclude the first character prefix.
            // Junk like "wxy" will be accepted but produce benign results.
            var width = format[1] - '0';

            if (format.Length == 3)
            {
                width *= 10;
                width += format[2] - '0';
            }

            if (width < 1)
            {
                return(string.Empty);
            }

            switch (format[0])
            {
            case 'w':
                return(GetLevelMoniker(_lowerCaseLevelMap, index, width));

            case 'u':
                return(GetLevelMoniker(_upperCaseLevelMap, index, width));

            case 't':
                return(GetLevelMoniker(_titleCaseLevelMap, index, width));

            default:
                return(Casing.Format(GetLevelMoniker(_titleCaseLevelMap, index), format));
            }
        }
示例#21
0
        public void LoweredLevelMessages(LogEventLevel level)
        {
            using (var log = new LogHelper())
            {
                using (TestCorrelator.CreateContext())
                {
                    ILogger downgradeLogger = new DowngradeErrorLogger(log.Logger);

                    var random = Guid.NewGuid();
                    var ex     = new Exception("Test");
                    downgradeLogger.Write(level, ex, "{level} log: {random}", level, random);
                    var logEvent = TestCorrelator.GetLogEventsFromCurrentContext().Single();
                    var message  = logEvent.RenderMessage();
                    Assert.Equal(LogEventLevel.Warning, logEvent.Level);
                    Assert.Equal(ex, logEvent.Exception);
                    Assert.Contains($"{level.ToString()} log: {random.ToString()}", message);
                }
            }
        }
 /// <summary>
 /// Creates the message.
 /// </summary>
 /// <param name="template">The template.</param>
 /// <param name="renderedMessage">The rendered message.</param>
 /// <param name="logEventLevel">The log event level.</param>
 /// <param name="color">The color.</param>
 /// <param name="counter">The counter.</param>
 /// <param name="occurredOn">The occurred on date.</param>
 /// <returns>A <see cref="JObject"/> from the message.</returns>
 public static JObject CreateMessage(string template, string renderedMessage, LogEventLevel logEventLevel,
                                     string color, int counter, string occurredOn)
 {
     return(new JObject
     {
         ["@type"] = "MessageCard",
         ["@context"] = "http://schema.org/extensions",
         ["title"] = "Integration Tests",
         ["text"] = renderedMessage,
         ["themeColor"] = color,
         ["sections"] = new JArray
         {
             new JObject
             {
                 ["title"] = "Properties",
                 ["facts"] = new JArray
                 {
                     new JObject
                     {
                         ["name"] = "Level",
                         ["value"] = logEventLevel.ToString()
                     },
                     new JObject
                     {
                         ["name"] = "MessageTemplate",
                         ["value"] = template
                     },
                     new JObject
                     {
                         ["name"] = "counter",
                         ["value"] = counter
                     },
                     new JObject
                     {
                         ["name"] = "Occurred on",
                         ["value"] = occurredOn
                     }
                 }
             }
         }
     });
 }
 /// <summary>
 /// Creates the message.
 /// </summary>
 /// <param name="template">The template.</param>
 /// <param name="renderedMessage">The rendered message.</param>
 /// <param name="logEventLevel">The log event level.</param>
 /// <param name="color">The color.</param>
 /// <param name="counter">The counter.</param>
 /// <param name="occurredOn">The occurred on date.</param>
 /// <returns>A <see cref="JsonElement"/> from the message.</returns>
 public static string CreateMessage(string template, string renderedMessage, LogEventLevel logEventLevel,
                                    string color, int counter, string occurredOn)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         using (Utf8JsonWriter writer = new Utf8JsonWriter(ms))
         {
             writer.WriteStartObject();
             writer.WriteString("@type", "MessageCard");
             writer.WriteString("@context", "http://schema.org/extensions");
             writer.WriteString("title", "Integration Tests");
             writer.WriteString("text", renderedMessage);
             writer.WriteString("themeColor", color);
             writer.WriteStartArray("sections");
             writer.WriteStartObject();
             writer.WriteString("title", "Properties");
             writer.WriteStartArray("facts");
             writer.WriteStartObject();
             writer.WriteString("name", "Level");
             writer.WriteString("value", logEventLevel.ToString());
             writer.WriteEndObject();
             writer.WriteStartObject();
             writer.WriteString("name", "MessageTemplate");
             writer.WriteString("value", template);
             writer.WriteEndObject();
             writer.WriteStartObject();
             writer.WriteString("name", "counter");
             writer.WriteString("value", counter.ToString());
             writer.WriteEndObject();
             writer.WriteStartObject();
             writer.WriteString("name", "Occurred on");
             writer.WriteString("value", occurredOn);
             writer.WriteEndObject();
             writer.WriteEndArray();  // end facts
             writer.WriteEndObject();
             writer.WriteEndArray();  // end sections
             writer.WriteEndObject();
         }
         return(Encoding.UTF8.GetString(ms.ToArray()));
     }
 }
示例#24
0
        public IActionResult LogLevel(LogEventLevel level)
        {
            var     serilogSettingsFile = Path.Combine(Directory.GetParent(Assembly.GetEntryAssembly().Location).FullName, "serilogsettings.json");
            JObject jobject;

            using (var reader = new StreamReader(serilogSettingsFile))
                using (var jsonReader = new JsonTextReader(reader))
                {
                    jobject = JObject.Load(jsonReader);
                    jobject.SelectToken("Serilog.MinimumLevel.Default").Replace(level.ToString());
                }

            using (var writer = new StreamWriter(serilogSettingsFile))
                using (var jsonWriter = new JsonTextWriter(writer))
                {
                    jsonWriter.Formatting = Formatting.Indented;
                    jobject.WriteTo(jsonWriter);
                }

            return(Ok());
        }
示例#25
0
        private void Log(
            string message,
            object data,
            Exception ex,
            Guid?correlationId,
            string source,
            LogEventLevel level,
            Action <string, LogMessage> logger)
        {
            var logMessage = new LogMessage
            {
                Application   = _appName,
                Data          = data,
                Level         = level.ToString(),
                Message       = message,
                Method        = source,
                Timestamp     = DateTime.Now,
                CorrelationId = (correlationId ?? Guid.NewGuid()).ToString(),
                Error         = ex
            };

            logger.Invoke("{@LogMessage}", logMessage);
        }
        public LogEventsAssertions WithLevel(LogEventLevel level, string because = "", params object[] becauseArgs)
        {
            var notMatched = Subject.Where(logEvent => logEvent.Level != level).ToList();

            var notMatchedText = "";

            if (notMatched.Any())
            {
                notMatchedText = string.Join(" and ",
                                             notMatched
                                             .GroupBy(logEvent => logEvent.Level,
                                                      logEvent => logEvent,
                                                      (key, values) => $"{values.Count()} with level \"{key}\""));
            }

            Execute.Assertion
            .BecauseOf(because, becauseArgs)
            .ForCondition(Subject.All(logEvent => logEvent.Level == level))
            .FailWith($"Expected instances of log message {{0}} to have level {{1}}, but found {notMatchedText}",
                      _messageTemplate,
                      level.ToString());

            return(this);
        }
示例#27
0
 private void ChangeLogLevel(LogEventLevel logLevel)
 {
     AgLog.LogLevelSwitch.MinimumLevel = logLevel;
     Log.Fatal($"Changed LogLevel to {logLevel.ToString()}");
 }
 internal RollingLogFile Next(TemplatedPathRoller roller, LogEventLevel? level = null)
 {
     this.Level = level;
     var fileName = roller.GetLogFilePath(DateTime.UtcNow, level, SequenceNumber + 1);
     return new RollingLogFile(fileName, DateTime.UtcNow, SequenceNumber + 1, level.HasValue ? level.ToString() : null);
 }
        /// <summary>
        /// 根据日志级别获取路径
        /// </summary>
        /// <param name="logEventLevel">日志级别</param>
        /// <returns></returns>
        private static string GetLogFilePathByLogLevel(LogEventLevel logEventLevel)
        {
            var datetimeNow = DateTime.Now;

            return($"Log/{logEventLevel.ToString()}/{datetimeNow.Year}-{datetimeNow.Month}/Day{datetimeNow.Day}/log.log");
        }
示例#30
0
 private static string LogFormatter(LogEventLevel level, string message, DateTime timestamp, Type scope, string method)
 {
     return($"[{timestamp:HH:mm:ss:fff}] [{new string(level.ToString().Take(1).ToArray())}] [{scope}->{method}()]: {message}");
 }
 private static string GetLevelTitle(LogEventLevel level)
 {
     return(level.ToString());
 }