Beispiel #1
0
        /// <inheritdoc />
        protected override void PostProcessing(ILoggingSinkOptions settings)
        {
            if (settings is NLogSinkOptions options)
            {
                if (options.OriginConfiguration != null)
                {
                    LogManager.Configuration = options.OriginConfiguration;
                }
                else if (!string.IsNullOrWhiteSpace(options.OriginConfigFilePath))
                {
                    LogManager.Configuration = new XmlLoggingConfiguration(options.OriginConfigFilePath);
                }
                else if (!string.IsNullOrWhiteSpace(ConfigFile))
                {
                    LogManager.Configuration = new XmlLoggingConfiguration(ConfigFile);
                }
                else
                {
                    LogManager.Configuration = new DefaultNLogConfiguration();
                }

                if (options.MinimumLevel.HasValue)
                {
                    LogManager.GlobalThreshold = LogLevelSwitcher.Switch(options.MinimumLevel.Value);
                }
            }
            else if (!string.IsNullOrWhiteSpace(ConfigFile))
            {
                LogManager.Configuration = new XmlLoggingConfiguration(ConfigFile);
            }
            else
            {
                LogManager.Configuration = new DefaultNLogConfiguration();
            }
        }
Beispiel #2
0
        public Task WriteAsync(ILogPayload payload, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (payload != null)
            {
                var legalityEvents = LogEventSinkFilter.Filter(payload, _sinkConfiguration).ToList();
                var source         = payload.SourceType.FullName;
                using (var logger = ExceptionlessClient.Default) {
                    foreach (var logEvent in legalityEvents)
                    {
                        var exception     = logEvent.Exception;
                        var level         = LogLevelSwitcher.Switch(logEvent.Level);
                        var stringBuilder = new StringBuilder();
                        using (var output = new StringWriter(stringBuilder, _formatProvider)) {
                            logEvent.RenderMessage(output, _sinkConfiguration.Rendering, _formatProvider);
                        }

                        var builder = logger.CreateLog(source, stringBuilder.ToString(), level);
                        builder.Target.Date = logEvent.Timestamp;

                        if (level == LogLevel.Fatal)
                        {
                            builder.MarkAsCritical();
                        }

                        if (exception != null)
                        {
                            builder.SetException(exception);
                        }

                        var legalityOpts = logEvent.GetAdditionalOperations(typeof(ExceptionlessPayloadClient), AdditionalOperationTypes.ForLogSink);
                        foreach (var opt in legalityOpts)
                        {
                            if (opt.GetOpt() is Func <EventBuilder, EventBuilder> eventBuilderFunc)
                            {
                                eventBuilderFunc.Invoke(builder);
                            }
                        }

                        foreach (var extra in logEvent.ExtraProperties)
                        {
                            var property = extra.Value;
                            if (property != null)
                            {
                                builder.SetProperty(property.Name, property.Value);
                            }
                        }

                        builder.PluginContextData.MergeContextData(logEvent.ContextData);

                        builder.Submit();
                    }
                }
            }

#if NET451
            return(Task.FromResult(true));
#else
            return(Task.CompletedTask);
#endif
        }
Beispiel #3
0
 private static Func <string, LogEventLevel, bool> As(Func <string, LogLevel, bool> originFilter)
 {
     if (originFilter == null)
     {
         return(null);
     }
     return((s, l) => originFilter(s, LogLevelSwitcher.Switch(l)));
 }
Beispiel #4
0
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="level">日志等级</param>
        /// <param name="content">日志内容</param>
        public void WriteLog(LogLevel level, ILogContent content)
        {
            var provider = GetFormatProvider();

            if (provider == null)
            {
                _logger.Log(LogLevelSwitcher.Switch(level), content);
                return;
            }
            _logger.Log(LogLevelSwitcher.Switch(level), provider, content);
        }
        /// <summary>
        /// 创建事件生成器
        /// </summary>
        /// <param name="level">平台日志等级</param>
        /// <param name="content">日志内容</param>
        private el.EventBuilder CreateBuilder(LogLevel level, ILogContent content)
        {
            if (content.Exception != null && (level == LogLevel.Error || level == LogLevel.Fatal))
            {
                return(_client.CreateException(content.Exception));
            }
            var builder = _client.CreateLog(GetMessage(content), LogLevelSwitcher.Switch(level));

            if (content.Exception != null && level == LogLevel.Warning)
            {
                builder.SetException(content.Exception);
            }
            return(builder);
        }
Beispiel #6
0
        /// <inheritdoc />
        public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
        {
            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }
            var messageTemplate = formatter(state, exception);

            if (string.IsNullOrWhiteSpace(messageTemplate))
            {
                return;
            }
            _logger.Write(eventId.ToEventId(), LogLevelSwitcher.Switch(logLevel), exception, messageTemplate,
                          LogEventSendMode.Customize, NullLogCallerInfo.Instance);
        }
        /// <inheritdoc />
        public async Task WriteAsync(ILogPayload payload, CancellationToken cancellationToken = default)
        {
            if (payload != null)
            {
                var legalityEvents = LogEventSinkFilter.Filter(payload, _sinkConfiguration).ToList();
                var logger         = TomatoClientManager.Get();

                if (logger == null)
                {
                    return;
                }

                foreach (var logEvent in legalityEvents)
                {
                    LogEventEnricherManager.Enricher(logEvent);
                    var stringBuilder = new StringBuilder();
                    using (var output = new StringWriter(stringBuilder, _formatProvider)) {
                        logEvent.RenderMessage(output, _sinkConfiguration.Rendering, _formatProvider);
                    }

                    var content = logEvent.ContextData?.ToString();

                    dynamic dynamicObj = null;

                    if (logEvent.ExtraProperties.Count > 0)
                    {
                        dynamicObj = new ExpandoObject();
                        foreach (var extra in logEvent.ExtraProperties)
                        {
                            var property = extra.Value;
                            if (property != null)
                            {
                                dynamicObj[property.Name] = property.Value.ToString();
                            }
                        }
                    }

                    await logger.WriteLogAsync(
                        logEvent.EventId.GetIntegerEventId(),
                        LogLevelSwitcher.Switch(logEvent.Level),
                        stringBuilder.ToString(),
                        content,
                        dynamicObj);
                }
            }
        }
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="level">日志等级</param>
        /// <param name="content">日志内容</param>
        /// <exception cref="NullReferenceException"></exception>
        public void WriteLog(LogLevel level, ILogContent content)
        {
            var provider      = GetFormatProvider();
            var logEventLevel = LogLevelSwitcher.Switch(level);

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

            _logger.Write(logEventLevel.SafeValue(), message);
        }
Beispiel #9
0
        /// <summary>
        /// 从Serilog日志事件创建事件构建器
        /// </summary>
        /// <param name="client">Exceptionless客户端</param>
        /// <param name="log">Serilog日志事件</param>
        public static EventBuilder CreateFromLogEvent(this ExceptionlessClient client, LogEvent log)
        {
            var message = log.RenderMessage();

            var builder = log.Exception != null
                ? client.CreateException(log.Exception)
                : client.CreateLog(log.GetSource(), message, LogLevelSwitcher.Switch(log.Level));

            builder.Target.Date = log.Timestamp;
            if (log.Level == LogEventLevel.Fatal)
            {
                builder.MarkAsCritical();
            }

            if (!string.IsNullOrWhiteSpace(message))
            {
                builder.SetMessage(message);
            }

            return(builder);
        }
Beispiel #10
0
        public Task WriteAsync(ILogPayload payload, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (payload != null)
            {
                var legalityEvents = LogEventSinkFilter.Filter(payload, _sinkConfiguration).ToList();
                var logger         = global::NLog.LogManager.GetLogger(payload.Name, payload.SourceType);

                foreach (var logEvent in legalityEvents)
                {
                    var exception     = logEvent.Exception;
                    var level         = LogLevelSwitcher.Switch(logEvent.Level);
                    var stringBuilder = new StringBuilder();
                    using (var output = new StringWriter(stringBuilder, _formatProvider)) {
                        logEvent.RenderMessage(output, _sinkConfiguration.Rendering, _formatProvider);
                    }

                    if (logEvent.ExtraProperties.Count > 0)
                    {
                        stringBuilder.AppendLine("Extra properties:");
                        foreach (var extra in logEvent.ExtraProperties)
                        {
                            var property = extra.Value;
                            if (property != null)
                            {
                                stringBuilder.AppendLine($"    {property}");
                            }
                        }
                    }

                    logger.Log(level, exception, stringBuilder.ToString());
                }
            }

#if NET451
            return(Task.FromResult(true));
#else
            return(Task.CompletedTask);
#endif
        }
        /// <summary>
        /// 配置日志级别
        /// </summary>
        /// <param name="source">Serilog日志配置</param>
        /// <param name="configuration">配置</param>
        public static LoggerConfiguration ConfigLogLevel(this LoggerConfiguration source, IConfiguration configuration)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            var section = configuration.GetSection("Logging:LogLevel");

            foreach (var item in section.GetChildren())
            {
                if (item.Key == "Default")
                {
                    source.MinimumLevel.ControlledBy(new LoggingLevelSwitch(LogLevelSwitcher.Switch(item.Value)));
                    continue;
                }
                source.MinimumLevel.Override(item.Key, LogLevelSwitcher.Switch(item.Value));
            }
            return(source);
        }
        /// <summary>提交.</summary>
        /// <param name="logEvent">日志事件</param>
        public void Emit(LogEvent logEvent)
        {
            if (logEvent == null || !_client.Configuration.IsValid)
            {
                return;
            }
            var minLogLevel = _client.Configuration.Settings.GetMinLogLevel(logEvent.GetSource());

            if (LogLevelSwitcher.Switch(logEvent.Level) < minLogLevel)
            {
                return;
            }

            var builder = _client
                          .CreateFromLogEvent(logEvent)
                          .AddTags(_defaultTags);

            if (_includeProperties && logEvent.Properties != null)
            {
                foreach (var property in logEvent.Properties)
                {
                    switch (property.Key)
                    {
                    case Constants.SourceContextPropertyName:
                        continue;

                    case Event.KnownDataKeys.UserInfo when property.Value is StructureValue uis && string.Equals(nameof(UserInfo), uis.TypeTag):
                        var userInfo = uis.FlattenProperties() as Dictionary <string, object>;
                        if (userInfo is null)
                        {
                            continue;
                        }
                        // 忽略数据属性
                        var identity = userInfo[nameof(UserInfo.Identity)] as string;
                        var name     = userInfo[nameof(UserInfo.Name)] as string;
                        if (!string.IsNullOrWhiteSpace(identity) || !string.IsNullOrWhiteSpace(name))
                        {
                            builder.SetUserIdentity(identity, name);
                        }
                        break;

                    case Event.KnownDataKeys.UserDescription when property.Value is StructureValue uds && string.Equals(nameof(UserDescription), uds.TypeTag):
                        var userDescription = uds.FlattenProperties() as Dictionary <string, object>;
                        if (userDescription is null)
                        {
                            continue;
                        }
                        // 忽略数据属性
                        var emailAddress = userDescription[nameof(UserDescription.EmailAddress)] as string;
                        var description  = userDescription[nameof(UserDescription.Description)] as string;
                        if (!string.IsNullOrWhiteSpace(emailAddress) || !string.IsNullOrWhiteSpace(description))
                        {
                            builder.SetUserDescription(emailAddress, description);
                        }
                        break;

                    default:
                        builder.SetProperty(property.Key, property.Value.FlattenProperties());
                        break;
                    }
                }
            }

            _additionalOperation?.Invoke(builder);
            builder.Submit();
        }
Beispiel #13
0
 /// <summary>
 /// Write log
 /// </summary>
 /// <param name="logLevel"></param>
 /// <param name="state"></param>
 /// <param name="exception"></param>
 public void Log(NHibernateLogLevel logLevel, NHibernateLogValues state, Exception exception)
 {
     _logger.Log(LogLevelSwitcher.Switch(logLevel), exception, state.ToString());
 }
Beispiel #14
0
 /// <inheritdoc />
 public override void Log(NpgsqlLogLevel level, int connectorId, string msg, Exception exception = null)
 {
     _logger.Log(LogLevelSwitcher.Switch(level), exception, msg, ctx => ctx.AddData("ConnectorId", connectorId));
 }
Beispiel #15
0
 /// <inheritdoc />
 public override bool IsEnabled(NpgsqlLogLevel level)
 {
     return(_minimumLevel != LogEventLevel.Off &&
            _logger.IsEnabled(LogLevelSwitcher.Switch(level)));
 }
Beispiel #16
0
 /// <summary>
 /// Checks if the given <paramref name="logLevel"/> is enabled.
 /// </summary>
 /// <param name="logLevel"></param>
 /// <returns></returns>
 public bool IsEnabled(NHibernateLogLevel logLevel) => _logger.IsEnabled(LogLevelSwitcher.Switch(logLevel));
        public static DbContextOptionsBuilder UseCosmosLogging(this DbContextOptionsBuilder builder, ILoggingServiceProvider loggingServiceProvider,
                                                               Func <string, LogLevel, bool> filter)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(new EfCoreLoggerWrapperProvider(loggingServiceProvider, UpstreamRenderingOptions,
                                                                      (s, l) => (_gloablFilter?.Invoke(s, l) ?? true) && (filter?.Invoke(s, LogLevelSwitcher.Switch(l)) ?? true)));
            builder.UseLoggerFactory(loggerFactory);

            return(builder);
        }
Beispiel #18
0
        public static void UseCosmosLogging(this DbContext db, Func <string, LogEventLevel, bool> filter, Func <string, object> loggerAct = null)
        {
            if (db == null)
            {
                throw new ArgumentNullException(nameof(db));
            }

            Func <string, LogEventLevel, bool> localFilter = (s, l) => (Settings?.Filter?.Invoke(s, l) ?? true) && (filter?.Invoke(s, l) ?? true);

            var internalLogger = LoggingServiceProvider?.GetLogger <DbContext>(localFilter, LogEventSendMode.Automatic, UpstreamRenderingOptions);

            if (internalLogger == null)
            {
                return;
            }

            var localFunc = GlobalSimpleLoggingInterceptor;

            localFunc += loggerAct;

            var logger = new SimpleLogger(internalLogger, localFunc);

            db.ConfigureLogging(s => logger.WriteLog(s, db.Database.GetDbConnection().Database), (s, l) => localFilter.Invoke(s, LogLevelSwitcher.Switch(l)));
        }
Beispiel #19
0
 /// <inheritdoc />
 public bool IsEnabled(LogLevel logLevel)
 {
     return(_logger.IsEnabled(LogLevelSwitcher.Switch(logLevel)));
 }
Beispiel #20
0
        /// <summary>
        /// 扩展属性
        /// </summary>
        /// <param name="logEvent">日志事件</param>
        /// <param name="propertyFactory">日志事件属性工厂</param>
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var property = propertyFactory.CreateProperty("LogLevel", LogLevelSwitcher.Switch(logEvent.Level));

            logEvent.AddOrUpdateProperty(property);
        }