コード例 #1
0
        public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception,
                                 Func <TState, Exception, string> formatter)
        {
            var level = ConvertLevel(logLevel);

            if (!_logger.IsEnabled(level))
            {
                return;
            }
            string        messageFormat;
            List <object> props;

            ParseState(state as IEnumerable <KeyValuePair <string, object> >, out messageFormat, out props);
            if (messageFormat == null)
            {
                messageFormat = formatter(state, exception);
            }
            IEnumerable <LogEventProperty> boundProps;
            MessageTemplate messageTemplate;

            _logger.BindMessageTemplate(messageFormat, props.ToArray(), out messageTemplate, out boundProps);
            var properties = new List <LogEventProperty>
            {
                new LogEventProperty("EventId", new ScalarValue(eventId.Id)),
                new LogEventProperty("EventName", new ScalarValue(eventId.Name)),
            };

            properties.AddRange(boundProps);
            var logEvent = new LogEvent(DateTimeOffset.Now, level, exception, messageTemplate, properties);

            _logger.Write(logEvent);
        }
コード例 #2
0
 public bool IsEnabled(LogLevel logLevel)
 {
     return(logLevel switch
     {
         LogLevel.Debug => _logger.IsEnabled(LogEventLevel.Debug),
         LogLevel.Information => _logger.IsEnabled(LogEventLevel.Information),
         LogLevel.Warning => _logger.IsEnabled(LogEventLevel.Warning),
         LogLevel.Error => _logger.IsEnabled(LogEventLevel.Error),    //made changes for custom error logging.
         LogLevel.Critical => _logger.IsEnabled(LogEventLevel.Fatal), //made changes for custom error logging.
         _ => throw new ArgumentException($"Unknown log level {logLevel}.", nameof(logLevel)),
     });
コード例 #3
0
 void WriteSerilog(LogEventLevel level, LogOutputProvider logOutputProvider)
 {
     if (_logger.IsEnabled(level))
     {
         _logger.Write(level, ObjectLogTemplate, logOutputProvider());
     }
 }
コード例 #4
0
ファイル: EsSubscription.cs プロジェクト: jesp209i/KajSpike
        public void Start()
        {
            var settings = new CatchUpSubscriptionSettings(2000, 500,
                                                           Log.IsEnabled(LogEventLevel.Verbose),
                                                           true, "try-out-subscription");

            _subscription = _connection.SubscribeToAllFrom(Position.Start, settings, EventAppeared);
        }
コード例 #5
0
 /// <summary>
 ///     Test if a certain LogLevels enum is enabled
 /// </summary>
 /// <param name="logLevel">LogLevels value</param>
 /// <param name="logSource">LogSource to check for</param>
 /// <returns>bool true if the LogLevels enum is enabled</returns>
 public override bool IsLogLevelEnabled(LogLevels logLevel, LogSource logSource = null)
 {
     Serilog.ILogger seriLogger = Log;
     if (logSource?.SourceType != null)
     {
         seriLogger = Log.ForContext(logSource.SourceType);
     }
     return(logLevel != LogLevels.None && seriLogger.IsEnabled(ConvertLevel(logLevel)));
 }
コード例 #6
0
        public async Task Start()
        {
            var settings = new CatchUpSubscriptionSettings(2000, 500,
                                                           Log.IsEnabled(LogEventLevel.Verbose),
                                                           false, "try-out-subscription");

            var position = await _checkpointStore.GetCheckpoint();

            _subscription = _connection.SubscribeToAllFrom(position, settings, EventAppeared);
        }
コード例 #7
0
                public bool IsEnabled(LogLevel logLevel)
                {
                    if (logLevel == LogLevel.None)
                    {
                        return(false);
                    }

                    var serilogLevel = levelMapping[logLevel];

                    return(logger.IsEnabled(serilogLevel));
                }
コード例 #8
0
        private void Initialize(IEventStoreConnection connection)
        {
            if (_log.IsEnabled(LogEventLevel.Information))
            {
                _log.Information("Initializing Cache");
            }

            _stateOfTheWorldContainer.IsStale = true;
            _stateOfTheWorldContainer.StateOfTheWorld.Clear();
            _isCaughtUp = false;

            _events = GetAllEvents(connection).Where(x => IsMatchingEventType(x.EventType))
                      .SubscribeOn(_eventLoopScheduler)
                      .Publish();

            _eventsSubscription.Disposable = _events.Subscribe(evt =>
            {
                UpdateStateOfTheWorld(_stateOfTheWorldContainer.StateOfTheWorld, evt);

                if (_isCaughtUp)
                {
                    _stateOfTheWorldUpdates.OnNext(_stateOfTheWorldContainer);
                }
            });
            _eventsConnection.Disposable = _events.Connect();
        }
コード例 #9
0
        public bool IsEnabledFor(LoggingEventType severityType)
        {
            switch (severityType)
            {
            case LoggingEventType.Information:
                return(_logger.IsEnabled(LogEventLevel.Information));

            case LoggingEventType.Debug:
                return(_logger.IsEnabled(LogEventLevel.Debug));

            case LoggingEventType.Warning:
                return(_logger.IsEnabled(LogEventLevel.Warning));

            case LoggingEventType.Error:
                return(_logger.IsEnabled(LogEventLevel.Error));

            case LoggingEventType.Fatal:
                return(_logger.IsEnabled(LogEventLevel.Fatal));

            case LoggingEventType.Trace:
                return(_logger.IsEnabled(LogEventLevel.Verbose));

            default:
                return(false);
            }
        }
コード例 #10
0
        /// <summary>
        /// Translates the log level from serilog to the web server log level
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <returns></returns>
        private LogLevel TranslateLogLevel(Serilog.ILogger logger)
        {
            if (logger.IsEnabled(Serilog.Events.LogEventLevel.Verbose))
            {
                return(LogLevel.Trace);
            }
            if (logger.IsEnabled(Serilog.Events.LogEventLevel.Debug))
            {
                return(LogLevel.Debug);
            }
            if (logger.IsEnabled(Serilog.Events.LogEventLevel.Information))
            {
                return(LogLevel.Info);
            }
            if (logger.IsEnabled(Serilog.Events.LogEventLevel.Warning))
            {
                return(LogLevel.Warning);
            }
            if (logger.IsEnabled(Serilog.Events.LogEventLevel.Error))
            {
                return(LogLevel.Error);
            }
            if (logger.IsEnabled(Serilog.Events.LogEventLevel.Fatal))
            {
                return(LogLevel.Fatal);
            }

            return(LogLevel.None);
        }
コード例 #11
0
        /// <summary>
        /// Returns true if outputFiles cannot have been built from inputFiles.
        /// </summary>
        /// <param name="outputFiles"></param>
        /// <param name="inputFiles"></param>
        /// <returns>True if outputFiles cannot have been built from inputFiles, false otherwise</returns>
        public static bool IsOutOfDate(this IEnumerable <string> outputFiles, IEnumerable <string> inputFiles)
        {
            outputFiles = outputFiles.ToList();
            var outputModified = outputFiles.LastWriteTimeUtc();
            var inputModified  = inputFiles.Except(outputFiles).LastWriteTimeUtc();
            var isOutOfDate    = outputModified < inputModified;

            if (Logger.IsEnabled(Serilog.Events.LogEventLevel.Debug))
            {
                Logger.Debug(@"IsOutOfDate: {isOutOfDate}

Input files:
{@inputFiles}

Output files:
{@outputFiles}",
                             isOutOfDate,
                             inputFiles.Select(_ => new { Path = _, Changed = _.LastWriteTimeUtc() }),
                             outputFiles.Select(_ => new { Path = _, Changed = _.LastWriteTimeUtc() }));
            }
            return(isOutOfDate);
        }
コード例 #12
0
        protected EventStoreCache(IObservable <IConnected <IEventStoreConnection> > eventStoreConnectionStream, ILogger log)
        {
            _log        = log;
            Disposables = new CompositeDisposable(_eventsConnection, _eventsSubscription);

            _connectionChanged = eventStoreConnectionStream.ObserveOn(_eventLoopScheduler)
                                 .Publish();

            Disposables.Add(_connectionChanged.Connect());

            Disposables.Add(_connectionChanged.Subscribe(x =>
            {
                if (x.IsConnected)
                {
                    if (_log.IsEnabled(LogEventLevel.Information))
                    {
                        _log.Information("Connected to Event Store");
                    }

                    Initialize(x.Value);
                }
                else
                {
                    if (_log.IsEnabled(LogEventLevel.Information))
                    {
                        _log.Information("Disconnected from Event Store");
                    }

                    if (!_stateOfTheWorldContainer.IsStale)
                    {
                        _stateOfTheWorldContainer.IsStale = true;
                        _stateOfTheWorldUpdates.OnNext(_stateOfTheWorldContainer);
                    }
                }
            }));
        }
コード例 #13
0
        async Task StartProjection(Projection projection)
        {
            var lastCheckpoint = await _checkpointStore.GetLastCheckpoint <Position>(projection);

            var settings = new CatchUpSubscriptionSettings(
                _maxLiveQueueSize,
                _readBatchSize,
                Log.IsEnabled(LogEventLevel.Verbose),
                false,
                projection);

            _connection.SubscribeToAllFrom(
                lastCheckpoint,
                settings,
                EventAppeared(projection),
                LiveProcessingStarted(projection),
                SubscriptionDropped(projection));
        }
コード例 #14
0
        public async Task Start()
        {
            var settings = new CatchUpSubscriptionSettings(
                2000, 500,
                Log.IsEnabled(LogEventLevel.Verbose),
                false, "try-out-subscription"
                );

            Log.Debug("Starting the projection manager...");

            var position = await _checkpointStore.GetCheckpoint();

            Log.Debug("Retrieved the checkpoint: {checkpoint}", position);

            _subscription = _connection.SubscribeToAllFrom(
                position,
                settings, EventAppeared
                );
            Log.Debug("Subscribed to $all stream");
        }
コード例 #15
0
        public void ReceiveMessages(Func <InitiativeCreatedEventArgs, CancellationToken, Task> initiativeCreatedHandler   = null,
                                    Func <WorkOrderCreatedEventArgs, CancellationToken, Task> workOrderCreatedHandler     = null,
                                    Func <WorkOrderUpdatedEventArgs, CancellationToken, Task> workOrderUpdatedHandler     = null,
                                    Func <InitiativeLoggedEventArgs, CancellationToken, Task> initiativeLoggedHandler     = null,
                                    Func <InitiativeStatusChangedEventArgs, CancellationToken, Task> statusChangedHandler = null,
                                    Func <InitiativeStatusDescriptionChangedEventArgs, CancellationToken, Task> statusDescriptionChangedHandler = null,
                                    Microsoft.Azure.ServiceBus.MessageHandlerOptions options = null)
        {
            if (_logger.IsEnabled(Serilog.Events.LogEventLevel.Information))
            {
                StringBuilder handlerNames = new StringBuilder();
                if (initiativeCreatedHandler != null)
                {
                    handlerNames.Append("initiativeCreatedHndler");
                }
                if (workOrderCreatedHandler != null)
                {
                    if (handlerNames.Length > 0)
                    {
                        handlerNames.Append(", ");
                    }
                    handlerNames.Append("workOrderCreatedHandler");
                }
                if (workOrderUpdatedHandler != null)
                {
                    if (handlerNames.Length > 0)
                    {
                        handlerNames.Append(", ");
                    }
                    handlerNames.Append("workOrderUpdatedHandler");
                }
                if (initiativeLoggedHandler != null)
                {
                    if (handlerNames.Length > 0)
                    {
                        handlerNames.Append(", ");
                    }
                    handlerNames.Append("initiativeLoggedHandler");
                }
                if (statusDescriptionChangedHandler != null)
                {
                    if (handlerNames.Length > 0)
                    {
                        handlerNames.Append(", ");
                    }
                    handlerNames.Append("statusDescriptionChangedHandler");
                }
                _logger.Information("Starting message pump with handlers " + handlerNames.ToString()); // + " on topic '{TopicName}' and subscription '{Subscription}'", _subscriptionClient.TopicPath, _subscriptionClient.SubscriptionName);
            }

            var messageHandlerOptions = options ?? new Microsoft.Azure.ServiceBus.MessageHandlerOptions(OnDefaultError);

            messageHandlerOptions.AutoComplete = false;
            _messageReceiver.RegisterMessageHandler(async(msg, token) =>
            {
                _logger.Information("Received service bus message {MessageId}: {Label}", msg.Id.ToString(), msg.Label);

                switch (msg.Label)
                {
                case InitiativeMessageSender.INITIATIVE_CREATED:
                    {
                        if (initiativeCreatedHandler != null)
                        {
                            await ReceiveInitiativeCreated(msg, token, initiativeCreatedHandler);
                        }
                        else
                        {
                            await _messageReceiver.CompleteAsync(msg.LockToken);
                        }
                        break;
                    }

                case InitiativeMessageSender.REMEDY_WORK_ITEM_CREATED:
                    if (workOrderCreatedHandler != null)
                    {
                        await ReceiveInitiativeWorkItemCreated(msg, token, workOrderCreatedHandler);
                    }
                    else
                    {
                        await _messageReceiver.CompleteAsync(msg.LockToken);
                    }
                    break;

                case InitiativeMessageSender.WORK_ORDER_UPDATED:
                    if (workOrderUpdatedHandler != null)
                    {
                        await ReceiveWorkOrderUpdated(msg, token, workOrderUpdatedHandler);
                    }
                    else
                    {
                        await _messageReceiver.CompleteAsync(msg.LockToken);
                    }
                    break;

                case InitiativeMessageSender.INITIATIVE_LOGGED:
                    if (initiativeLoggedHandler != null)
                    {
                        await ReceiveInitiativeLogged(msg, token, initiativeLoggedHandler);
                    }
                    else
                    {
                        await _messageReceiver.CompleteAsync(msg.LockToken);
                    }
                    break;

                case InitiativeMessageSender.STATUS_CHANGED:
                    if (statusChangedHandler != null)
                    {
                        await ReceiveInitiativeStatusChanged(msg, token, statusChangedHandler);
                    }
                    else
                    {
                        await _messageReceiver.CompleteAsync(msg.LockToken);
                    }
                    break;

                case InitiativeMessageSender.STATUS_DESCRIPTION_CHANGED:
                    if (statusDescriptionChangedHandler != null)
                    {
                        await ReceiveInitiativeStatusDescriptionChanged(msg, token, statusDescriptionChangedHandler);
                    }
                    else
                    {
                        await _messageReceiver.CompleteAsync(msg.LockToken);
                    }
                    break;

                default:
                    {
                        await _messageReceiver.DeadLetterAsync(msg.LockToken, $"Unknown message type: { msg.Label }");
                        break;
                    }
                }
            }, messageHandlerOptions);
        }
コード例 #16
0
ファイル: Logger.cs プロジェクト: EsWork/Es.Logging
 public bool IsEnabled(LogLevel logLevel)
 {
     return(_logger.IsEnabled(GetLogLevel(logLevel)));
 }
コード例 #17
0
        public bool IsEnabled(Serilog.Events.LogEventLevel level)
        {
            var r = _logger?.IsEnabled(level);

            return(r ?? false);
        }
コード例 #18
0
 public bool IsEnabled(LogLevel logLevel)
 {
     return(_logger.IsEnabled(ConvertLevel(logLevel)));
 }
コード例 #19
0
 public bool IsEnabled(LogLevel level)
 {
     return(level >= minLogLevel && logger.IsEnabled(ToLevel(level)));
 }
コード例 #20
0
        public void Log(LogEntry entry)
        {
            //see if we can log anything, else exit early
            if (!_logger.IsEnabled(LogEventLevel.Fatal))
            {
                return;
            }

            if (entry.Exception == null)
            {
                if (entry.Severity == LoggingEventType.Trace && _logger.IsEnabled(LogEventLevel.Verbose))
                {
                    _logger.Verbose(entry.Message);
                }
                else if (entry.Severity == LoggingEventType.Debug && _logger.IsEnabled(LogEventLevel.Debug))
                {
                    _logger.Debug(entry.Message);
                }
                else if (entry.Severity == LoggingEventType.Information && _logger.IsEnabled(LogEventLevel.Information))
                {
                    _logger.Information(entry.Message);
                }
                else if (entry.Severity == LoggingEventType.Warning && _logger.IsEnabled(LogEventLevel.Warning))
                {
                    _logger.Warning(entry.Message);
                }
                else if (entry.Severity == LoggingEventType.Error && _logger.IsEnabled(LogEventLevel.Error))
                {
                    _logger.Error(entry.Message);
                }
                else if (entry.Severity == LoggingEventType.Fatal && _logger.IsEnabled(LogEventLevel.Fatal))
                {
                    _logger.Fatal(entry.Message);
                }
            }
            else
            {
                if (entry.Severity == LoggingEventType.Trace && _logger.IsEnabled(LogEventLevel.Verbose))
                {
                    _logger.Verbose(entry.Exception, entry.Message);
                }
                else if (entry.Severity == LoggingEventType.Debug && _logger.IsEnabled(LogEventLevel.Debug))
                {
                    _logger.Debug(entry.Exception, entry.Message);
                }
                else if (entry.Severity == LoggingEventType.Information && _logger.IsEnabled(LogEventLevel.Information))
                {
                    _logger.Information(entry.Exception, entry.Message);
                }
                else if (entry.Severity == LoggingEventType.Warning && _logger.IsEnabled(LogEventLevel.Warning))
                {
                    _logger.Warning(entry.Message, entry.Exception);
                }
                else if (entry.Severity == LoggingEventType.Error && _logger.IsEnabled(LogEventLevel.Error))
                {
                    _logger.Error(entry.Message, entry.Exception);
                }
                else if (entry.Severity == LoggingEventType.Fatal && _logger.IsEnabled(LogEventLevel.Fatal))
                {
                    _logger.Fatal(entry.Message, entry.Exception);
                }
            }
        }
コード例 #21
0
 public bool IsEnabled(LogLevel level)
 {
     return(_logger.IsEnabled(level.AsSerilogLevel()));
 }