コード例 #1
0
            public void Log <TState>(LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
            {
                // Write the information to the system trace
                string formattedString = formatter(state, exception);

                switch (logLevel)
                {
                case LogLevel.Information:
                case LogLevel.Debug:
                case LogLevel.Trace:
                    System.Diagnostics.Trace.TraceInformation(formattedString);
                    break;

                case LogLevel.Error:
                case LogLevel.Critical:
                    System.Diagnostics.Trace.TraceError(formattedString);
                    if (exception != null)
                    {
                        System.Diagnostics.Trace.TraceError(exception.ToString());
                    }
                    break;

                case LogLevel.Warning:
                    System.Diagnostics.Trace.TraceWarning(formattedString);
                    if (exception != null)
                    {
                        System.Diagnostics.Trace.TraceWarning(exception.ToString());
                    }
                    break;
                }
            }
コード例 #2
0
        public void Log <TState>(LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
        {
            string tag = "";

            switch (logLevel)
            {
            case LogLevel.Critical:
                tag = string.Format(_tag, "crit");
                break;

            case LogLevel.Debug:
                tag = string.Format(_tag, "debug");
                break;

            case LogLevel.Error:
                tag = string.Format(_tag, "err");
                break;

            case LogLevel.Information:
                tag = string.Format(_tag, "info");
                break;

            case LogLevel.Trace:
                tag = string.Format(_tag, "trace");
                break;

            case LogLevel.Warning:
                tag = string.Format(_tag, "warn");
                break;

            default:
                return;
            }
            Console.WriteLine(tag + formatter(state, exception));
        }
コード例 #3
0
        async Task IListener.StartAsync(CancellationToken cancellationToken)
        {
retry:

            using (var scope = logger.BeginScope("IListener"))
            {
                var eventId = new Microsoft.Extensions.Logging.EventId(1);
                logger.LogInformation("StartAsync");

                try
                {
                    var credentials = CreatorService.GetCredentials(triggerAttribute);
                    var tasks       = Enumerable.Range(1, triggerAttribute.NrListeners).Select(c => StartListener(credentials, cancellationToken));

                    await Task.WhenAll(tasks);
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, ex.Message);
                }
            }

            System.Threading.Thread.Sleep(30 * 1000);
            goto retry;
        }
コード例 #4
0
        public void Log <TState>(ML.LogLevel logLevel, ML.EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
        {
            var msg = formatter(state, exception);

            switch (logLevel)
            {
            case ML.LogLevel.Critical:
                logger.Fatal(msg);
                return;

            case ML.LogLevel.Debug:
                logger.Debug(msg);
                return;

            case ML.LogLevel.Error:
                logger.Error(msg);
                return;

            case ML.LogLevel.Information:
                logger.Info(msg);
                return;

            case ML.LogLevel.Trace:
                logger.Trace(msg);
                return;

            case ML.LogLevel.Warning:
                logger.Warn(msg);
                return;
            }
        }
コード例 #5
0
        /// <summary>
        /// Composes the rolbar package.
        /// </summary>
        /// <typeparam name="TState">The type of the t state.</typeparam>
        /// <param name="eventId">The event identifier.</param>
        /// <param name="state">The state.</param>
        /// <param name="exception">The exception.</param>
        /// <param name="formatter">The formatter.</param>
        /// <returns>IRollbarPackage (if any) or null.</returns>
        protected override IRollbarPackage?ComposeRollbarPackage <TState>(
            mslogging.EventId eventId,
            TState state,
            Exception exception,
            Func <TState, Exception, string> formatter
            )
        {
            IRollbarPackage?package = base.ComposeRollbarPackage(eventId, state, exception, formatter);

            if (package != null)
            {
                var httpContext = _httpContextAccessor?.HttpContext;
                if (httpContext != null)
                {
                    if (httpContext.Request != null)
                    {
                        package = new HttpRequestPackageDecorator(package, httpContext.Request, true);
                    }
                    if (httpContext.Response != null)
                    {
                        package = new HttpResponsePackageDecorator(package, httpContext.Response, true);
                    }
                }
            }

            return(package);
        }
コード例 #6
0
        void MSLOGGING.ILogger.Log <TState>(MSLOGGING.LogLevel logLevel, MSLOGGING.EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
        {
            var text = formatter(state, exception);

            lock (_Mutex) { _Log.Add(text); }

            _RaiseChanged(nameof(Log));
        }
コード例 #7
0
 public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
 {
     Entries.Add(new LogEntry
     {
         LogLevel = logLevel,
         EventId  = eventId,
         Message  = formatter?.Invoke(state, exception)
     });
 }
コード例 #8
0
 public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, String> formatter)
 {
     Logger.Log(
         LogLevelMapper.Map(logLevel),
         EventIdMapper.Map(eventId),
         MapState(logLevel, state, exception, formatter),
         exception,
         CategoryName != null ? new LogSource(CategoryName) : default
         );
 }
コード例 #9
0
        /// <summary>
        /// Composes the rolbar package.
        /// </summary>
        /// <typeparam name="TState">The type of the t state.</typeparam>
        /// <param name="eventId">The event identifier.</param>
        /// <param name="state">The state.</param>
        /// <param name="exception">The exception.</param>
        /// <param name="formatter">The formatter.</param>
        /// <returns>IRollbarPackage (if any) or null.</returns>
        protected virtual IRollbarPackage ComposeRolbarPackage <TState>(
            mslogging.EventId eventId
            , TState state
            , Exception exception
            , Func <TState, Exception, string> formatter
            )
        {
            string message = null;

            if (formatter != null)
            {
                message = formatter(state, exception);
            }

            IRollbarPackage rollbarPackage = null;

            if (exception != null)
            {
                rollbarPackage = new ExceptionPackage(exception, exception.Message);
            }
            else if (!string.IsNullOrWhiteSpace(message))
            {
                rollbarPackage = new MessagePackage(message, message);
            }
            else
            {
                return(null); //nothing to report...
            }

            Dictionary <string, object> customProperties = new Dictionary <string, object>();

            customProperties.Add(
                "LogEventID"
                , $"{eventId.Id}" + (string.IsNullOrWhiteSpace(eventId.Name) ? string.Empty : $" ({eventId.Name})")
                );
            if (exception != null && message != null)
            {
                customProperties.Add("LogMessage", message);
            }
            if (!string.IsNullOrWhiteSpace(this._name))
            {
                customProperties.Add("RollbarLoggerName", this._name);
            }
            if (customProperties.Count > 0)
            {
                rollbarPackage = new CustomKeyValuePackageDecorator(rollbarPackage, customProperties);
            }

            return(rollbarPackage);
        }
コード例 #10
0
        public void Log <TState>(Logging.LogLevel logLevel, Logging.EventId eventId, TState state,
                                 Exception exception, Func <TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }
            string message = null;

            if (null != formatter)
            {
                message = formatter(state, exception);
            }
            if (!string.IsNullOrEmpty(message) || exception != null)
            {
                switch (logLevel)
                {
                case Logging.LogLevel.Critical:
                    _log.Fatal(message);
                    break;

                case Logging.LogLevel.Debug:
                case Logging.LogLevel.Trace:
                    _log.Debug(message);
                    break;

                case Logging.LogLevel.Error:
                    _log.Error(message);
                    break;

                case Logging.LogLevel.Information:
                    _log.Info(message);
                    break;

                case Logging.LogLevel.Warning:
                    _log.Warn(message);
                    break;

                default:
                    _log.Warn($"Encountered unknown log level {logLevel}, writing out as Info.");
                    _log.Info(message, exception);
                    break;
                }
            }
        }
コード例 #11
0
        /// <summary>
        /// Writes a log entry.
        /// </summary>
        /// <typeparam name="TState"></typeparam>
        /// <param name="logLevel">Entry will be written on this level.</param>
        /// <param name="eventId">Id of the event.</param>
        /// <param name="state">The entry to be written. Can be also an object.</param>
        /// <param name="exception">The exception related to this entry.</param>
        /// <param name="formatter">Function to create a <c>string</c> message of the <paramref name="state" /> and <paramref name="exception" />.</param>
        public void Log <TState>(
            mslogging.LogLevel logLevel
            , mslogging.EventId eventId
            , TState state
            , Exception exception
            , Func <TState, Exception, string> formatter
            )
        {
            if (!this.IsEnabled(logLevel))
            {
                return;
            }

            if (object.Equals(state, default(TState)) && exception == null)
            {
                return;
            }

            if (RollbarScope.Current != null &&
                RollbarInfrastructure.Instance.Config.RollbarInfrastructureOptions.MaxItems > 0
                )
            {
                RollbarScope.Current.IncrementLogItemsCount();
                if (RollbarScope.Current.LogItemsCount == RollbarInfrastructure.Instance.Config.RollbarInfrastructureOptions.MaxItems)
                {
                    // the Rollbar SDK just reached MaxItems limit, report this fact and pause further logging within this scope:
                    RollbarLocator.RollbarInstance.Warning(RollbarScope.MaxItemsReachedWarning);
                    return;
                }
                else if (RollbarScope.Current.LogItemsCount > RollbarInfrastructure.Instance.Config.RollbarInfrastructureOptions.MaxItems)
                {
                    // the Rollbar SDK already exceeded MaxItems limit, do not log for this scope:
                    return;
                }
            }

            IRollbarPackage?rollbarPackage = this.ComposeRollbarPackage(eventId, state, exception, formatter);

            if (rollbarPackage != null)
            {
                var rollbarErrorLevel = ConverterUtil.ToRollbarErrorLevel(logLevel);

                this._rollbar.Log(rollbarErrorLevel, rollbarPackage);
            }
        }
コード例 #12
0
        /// <summary>
        /// Composes the rolbar package.
        /// </summary>
        /// <typeparam name="TState">The type of the t state.</typeparam>
        /// <param name="eventId">The event identifier.</param>
        /// <param name="state">The state.</param>
        /// <param name="exception">The exception.</param>
        /// <param name="formatter">The formatter.</param>
        /// <returns>IRollbarPackage (if any) or null.</returns>
        protected override IRollbarPackage ComposeRolbarPackage <TState>(
            mslogging.EventId eventId,
            TState state,
            Exception exception,
            Func <TState, Exception, string> formatter
            )
        {
            IRollbarPackage package = base.ComposeRolbarPackage(eventId, state, exception, formatter);

            var currentContext = GetCurrentContext();

            if (currentContext != null)
            {
                package = new RollbarHttpContextPackageDecorator(package, currentContext, true);
            }

            return(package);
        }
コード例 #13
0
            public void Log <TState>(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
            {
                if (this.IsEnabled(logLevel))
                {
                    this.logger.Log(logLevel, eventId, state, exception, formatter);

                    if (this.providerFactory.TraceToConsole || this.providerFactory.TraceToBlob)
                    {
                        string formattedString = $"{DateTime.UtcNow:o} {this.prefix}s{(int)logLevel} {formatter(state, exception)}";

                        if (this.providerFactory.TraceToConsole)
                        {
                            System.Console.WriteLine(formattedString);
                        }

                        NetheriteProviderFactory.BlobLogger?.WriteLine(formattedString);
                    }
                }
            }
コード例 #14
0
        public void Log <TState>(LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
        {
            // quit if not enabled
            if (this.logLevelLimit <= logLevel)
            {
                // pass through to the ILogger
                this.logger.Log(logLevel, eventId, state, exception, formatter);

                // additionally, if etw is enabled, pass on to ETW
                if (EtwSource.Log.IsEnabled())
                {
                    string details = formatter(state, exception);

                    switch (logLevel)
                    {
                    case LogLevel.Trace:
                        EtwSource.Log.EventHubsTrace(this.account, this.taskHub, this.eventHubsNamespace, details, TraceUtils.ExtensionVersion);
                        break;

                    case LogLevel.Debug:
                        EtwSource.Log.EventHubsDebug(this.account, this.taskHub, this.eventHubsNamespace, details, TraceUtils.ExtensionVersion);
                        break;

                    case LogLevel.Information:
                        EtwSource.Log.EventHubsInformation(this.account, this.taskHub, this.eventHubsNamespace, details, TraceUtils.ExtensionVersion);
                        break;

                    case LogLevel.Warning:
                        EtwSource.Log.EventHubsWarning(this.account, this.taskHub, this.eventHubsNamespace, details, TraceUtils.ExtensionVersion);
                        break;

                    case LogLevel.Error:
                    case LogLevel.Critical:
                        EtwSource.Log.EventHubsError(this.account, this.taskHub, this.eventHubsNamespace, details, TraceUtils.ExtensionVersion);
                        break;

                    default:
                        break;
                    }
                }
            }
        }
コード例 #15
0
            public void Log <TState>(Microsoft.Extensions.Logging.LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
            {
                LastLogLevel     = logLevel;
                LastLogEventId   = eventId;
                LastLogMessage   = formatter(state, exception);
                LastLogException = exception;
                var propertiesList = (state as IReadOnlyList <KeyValuePair <string, object> >);

                LastLogProperties = propertiesList?.ToList();
                for (int i = 0; i < propertiesList?.Count; ++i)
                {
                    var property = propertiesList[i];
                    if (property.Key != LastLogProperties[i].Key)
                    {
                        throw new ArgumentException($"Property key mismatch {LastLogProperties[i].Key} <-> {property.Key}");
                    }
                    if (property.Value != LastLogProperties[i].Value)
                    {
                        throw new ArgumentException($"Property Value mismatch {LastLogProperties[i].Value} <-> {property.Value}");
                    }
                }
            }
コード例 #16
0
ファイル: LogSinkLogger.cs プロジェクト: kentcb/PCLMock
        public void Log <TState>(
            MS.LogLevel logLevel,
            MS.EventId eventId,
            TState state,
            Exception exception,
            Func <TState, Exception, string> formatter)
        {
            if (logLevel == MS.LogLevel.Trace)
            {
                return;
            }

            var message = formatter(state, exception);

            // Very annoyingly, MSBuild appends new lines onto messages itself.
            if (message.EndsWith("\r\n"))
            {
                message = message.Substring(0, message.Length - 2);
            }

            switch (logLevel)
            {
            case MS.LogLevel.Debug:
                logSink.Debug(message);
                break;

            case MS.LogLevel.Information:
                logSink.Info(message);
                break;

            case MS.LogLevel.Warning:
                logSink.Warn(message);
                break;

            default:
                logSink.Error(message);
                break;
            }
        }
コード例 #17
0
 /// <summary>
 /// Indicates whether the current object is equal to another object of the same type. Two events are equal if they have the same id.
 /// </summary>
 /// <param name="other">An object to compare with this object.</param>
 /// <returns><see langword="true" /> if the current object is equal to the other parameter; otherwise, <see langword="false" />.</returns>
 public bool Equals(EventId other)
 {
     return(Id == other.Id);
 }
コード例 #18
0
 public static void LogTraceWithData(this ILogger logger, EventId eventId, string message, Exception exception = null, params object[] args)
 {
     logger.Log(LogLevel.Trace, eventId, args, exception, (_, __) => message);
 }
コード例 #19
0
ファイル: LogManager.cs プロジェクト: sanfran627/ReactSample
 public void Log <TState>(LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
 {
 }
コード例 #20
0
        /// <summary>
        /// Writes a log entry.
        /// </summary>
        /// <typeparam name="TState"></typeparam>
        /// <param name="logLevel">Entry will be written on this level.</param>
        /// <param name="eventId">Id of the event.</param>
        /// <param name="state">The entry to be written. Can be also an object.</param>
        /// <param name="exception">The exception related to this entry.</param>
        /// <param name="formatter">Function to create a <c>string</c> message of the <paramref name="state" /> and <paramref name="exception" />.</param>
        public void Log <TState>(
            mslogging.LogLevel logLevel
            , mslogging.EventId eventId
            , TState state
            , Exception exception
            , Func <TState, Exception, string> formatter
            )
        {
            if (!this.IsEnabled(logLevel))
            {
                return;
            }

            if (state == null && exception == null)
            {
                return;
            }

            if (RollbarScope.Current != null &&
                RollbarLocator.RollbarInstance.Config.MaxItems > 0
                )
            {
                RollbarScope.Current.IncrementLogItemsCount();
                if (RollbarScope.Current.LogItemsCount == RollbarLocator.RollbarInstance.Config.MaxItems)
                {
                    // the Rollbar SDK just reached MaxItems limit, report this fact and pause further logging within this scope:
                    RollbarLocator.RollbarInstance.Warning(RollbarScope.MaxItemsReachedWarning);
                    return;
                }
                else if (RollbarScope.Current.LogItemsCount > RollbarLocator.RollbarInstance.Config.MaxItems)
                {
                    // the Rollbar SDK already exceeded MaxItems limit, do not log for this scope:
                    return;
                }
            }

            // let's custom build the Data object that includes the exception
            // along with the current HTTP request context:

            string message = null;

            if (formatter != null)
            {
                message = formatter(state, exception);
            }

            Rollbar.DTOs.Body payloadBody = null;
            if (exception != null)
            {
                payloadBody = new DTOs.Body(exception);
            }
            else if (!string.IsNullOrWhiteSpace(message))
            {
                payloadBody = new DTOs.Body(new DTOs.Message(message));
            }
            else
            {
                return; //nothing to report...
            }

            Dictionary <string, object> customProperties = new Dictionary <string, object>();

            customProperties.Add(
                "LogEventID"
                , $"{eventId.Id}" + (string.IsNullOrWhiteSpace(eventId.Name) ? string.Empty : $" ({eventId.Name})")
                );
            if (exception != null && message != null)
            {
                customProperties.Add("LogMessage", message);
            }

            var currentContext = GetCurrentContext();

            Dictionary <string, object> customRequestFields = null;

            if (currentContext != null)
            {
                customRequestFields = new Dictionary <string, object>();
                customRequestFields.Add("httpRequestTimestamp", currentContext.Timestamp);
                if (currentContext.HttpAttributes != null)
                {
                    customRequestFields.Add("httpRequestID", currentContext.HttpAttributes.RequestID);
                    customRequestFields.Add("statusCode", currentContext.HttpAttributes.StatusCode);
                    customRequestFields.Add("scheme", currentContext.HttpAttributes.Scheme);
                    customRequestFields.Add("protocol", currentContext.HttpAttributes.Protocol);
                }
            }

            var requestDto = new DTOs.Request(customRequestFields, currentContext?.HttpAttributes);

            DTOs.Data dataDto = new DTOs.Data(
                config: RollbarLocator.RollbarInstance.Config
                , body: payloadBody
                , custom: customProperties
                , request: requestDto
                )
            {
                Level = RollbarLogger.Convert(logLevel),
            };

            // log the Data object (the exception + the HTTP request data):
            RollbarLocator.RollbarInstance.Log(dataDto);
        }
コード例 #21
0
 public void Log <TState>(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) where TState : LogEntryParameters
 {
     _logger.Log(logLevel, eventId, state, exception, formatter);
 }
コード例 #22
0
        /// <summary>
        /// Writes a log entry.
        /// </summary>
        /// <typeparam name="TState"></typeparam>
        /// <param name="logLevel">Entry will be written on this level.</param>
        /// <param name="eventId">Id of the event.</param>
        /// <param name="state">The entry to be written. Can be also an object.</param>
        /// <param name="exception">The exception related to this entry.</param>
        /// <param name="formatter">Function to create a <c>string</c> message of the <paramref name="state" /> and <paramref name="exception" />.</param>
        public void Log <TState>(
            mslogging.LogLevel logLevel
            , mslogging.EventId eventId
            , TState state
            , Exception exception
            , Func <TState, Exception, string> formatter
            )
        {
            if (!this.IsEnabled(logLevel))
            {
                return;
            }

            if (object.Equals(state, default(TState)) && exception == null)
            {
                return;
            }

            if (RollbarScope.Current != null &&
                RollbarLocator.RollbarInstance.Config.MaxItems > 0
                )
            {
                RollbarScope.Current.IncrementLogItemsCount();
                if (RollbarScope.Current.LogItemsCount == RollbarLocator.RollbarInstance.Config.MaxItems)
                {
                    // the Rollbar SDK just reached MaxItems limit, report this fact and pause further logging within this scope:
                    RollbarLocator.RollbarInstance.Warning(RollbarScope.MaxItemsReachedWarning);
                    return;
                }
                else if (RollbarScope.Current.LogItemsCount > RollbarLocator.RollbarInstance.Config.MaxItems)
                {
                    // the Rollbar SDK already exceeded MaxItems limit, do not log for this scope:
                    return;
                }
            }

            // let's custom build the Data object that includes the exception
            // along with the current HTTP request context:

            string message = null;

            if (formatter != null)
            {
                message = formatter(state, exception);
            }

            IRollbarPackage rollbarPackage = null;

            if (exception != null)
            {
                rollbarPackage = new ExceptionPackage(exception, exception.Message);
            }
            else if (!string.IsNullOrWhiteSpace(message))
            {
                rollbarPackage = new MessagePackage(message, message);
            }
            else
            {
                return; //nothing to report...
            }

            Dictionary <string, object> customProperties = new Dictionary <string, object>();

            customProperties.Add(
                "LogEventID"
                , $"{eventId.Id}" + (string.IsNullOrWhiteSpace(eventId.Name) ? string.Empty : $" ({eventId.Name})")
                );
            if (exception != null && message != null)
            {
                customProperties.Add("LogMessage", message);
            }
            if (customProperties.Count > 0)
            {
                rollbarPackage = new CustomKeyValuePackageDecorator(rollbarPackage, customProperties);
            }

            var currentContext = GetCurrentContext();

            if (currentContext != null)
            {
                rollbarPackage = new RollbarHttpContextPackageDecorator(rollbarPackage, currentContext, true);
            }

            var rollbarErrorLevel = RollbarLogger.Convert(logLevel);

            RollbarLocator.RollbarInstance.Log(rollbarErrorLevel, rollbarPackage);
        }
コード例 #23
0
 public static void LogTraceWithData(this ILogger logger, EventId eventId, string message, params object[] args)
 {
     logger.LogTraceWithData(eventId, message, default, args);
コード例 #24
0
        /// <summary>
        /// </summary>
        /// <param name="logLevel"></param>
        /// <param name="eventId"></param>
        /// <param name="state"></param>
        /// <param name="exception"></param>
        /// <param name="formatter"></param>
        public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception,
                                 Func <TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }

            dynamic message = new JObject();

            if (applicationName != null)
            {
                message.name = applicationName;
            }

            if (environment != null)
            {
                message.env = environment;
            }

            if (options.IncludeLogLevel)
            {
                message.level = logLevel.ToBunyanLogLevel();
            }

            if (options.IncludeCategory)
            {
                message.category_name = categoryName;
            }

            message.pid = Process.GetCurrentProcess().Id;

            message.hostname = hostname;

            if (state.GetType().Name.ToLower() == "jobject")
            {
                using (var enumerator = (state as JObject)?.GetEnumerator())
                {
                    if (enumerator == null)
                    {
                        return;
                    }
                    while (enumerator.MoveNext())
                    {
                        var current = enumerator.Current;
                        message[current.Key.ToLower()] = current.Value;
                    }
                }
            }
            else
            {
                message.msg = formatter.Invoke(state, exception);
            }

            if (options.IncludeNewline)
            {
            }

            message.time = DateTime.UtcNow;

            if (exception != null)
            {
                message.err = exception.ToString();
            }

            if (eventId.Id != 0)
            {
                message.event_id   = eventId.Id;
                message.event_name = eventId.Name;
            }

            message.v = 0;

            string finalText;

            try
            {
                finalText = JsonConvert.SerializeObject(message, Formatting.None, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore,
                });
            }
#pragma warning disable 168
            catch (Exception e)
#pragma warning restore 168
            {
                return; // suppressing error here is intentional
            }

            Amazon.Lambda.Core.LambdaLogger.Log(finalText);
        }
コード例 #25
0
 public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
 {
     LastLevel   = logLevel;
     LastMessage = state.ToString();
 }
コード例 #26
0
        /// <summary>
        /// Creates a delegate which can be invoked for logging a message.
        /// </summary>
        /// <typeparam name="T1">The type of the first parameter passed to the named format string.</typeparam>
        /// <typeparam name="T2">The type of the second parameter passed to the named format string.</typeparam>
        /// <typeparam name="T3">The type of the third parameter passed to the named format string.</typeparam>
        /// <param name="logLevel">The <see cref="LogLevel"/></param>
        /// <param name="eventId">The event id</param>
        /// <param name="formatString">The named format string</param>
        /// <returns>A delegate which when invoked creates a log message.</returns>
        public static Action <ILogger, T1, T2, T3, Exception> Define <T1, T2, T3>(LogLevel logLevel, EventId eventId, string formatString)
        {
            var formatter = CreateLogValuesFormatter(formatString, expectedNamedParameterCount: 3);

            void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, Exception exception)
            {
                logger.Log(logLevel, eventId, new LogValues <T1, T2, T3>(formatter, arg1, arg2, arg3), exception, LogValues <T1, T2, T3> .Callback);
            }

            return((logger, arg1, arg2, arg3, exception) =>
            {
                if (logger.IsEnabled(logLevel))
                {
                    Log(logger, arg1, arg2, arg3, exception);
                }
            });
        }
コード例 #27
0
        /// <inheritdoc />
        public void LogException(IErrorDetail detail, Exception ex = null)
        {
            if (_exceptionDataProvider.LoggingEnabled)
            {
                var eventId = new Microsoft.Extensions.Logging.EventId(detail.EventId.Id, detail.EventId.Name);

                switch (detail.LogLevel)
                {
                case LogLevel.Critical:
                    if (ex == null)
                    {
                        _exceptionLogger.LogCritical(eventId, detail.Message);
                    }
                    else
                    {
                        _exceptionLogger.LogCritical(eventId, ex, detail.Message);
                    }
                    break;

                case LogLevel.Debug:
                    if (ex == null)
                    {
                        _exceptionLogger.LogDebug(eventId, detail.Message);
                    }
                    else
                    {
                        _exceptionLogger.LogDebug(eventId, ex, detail.Message);
                    }
                    break;

                case LogLevel.Error:
                    if (ex == null)
                    {
                        _exceptionLogger.LogError(eventId, detail.Message);
                    }
                    else
                    {
                        _exceptionLogger.LogError(eventId, ex, detail.Message);
                    }
                    break;

                case LogLevel.Information:
                    if (ex == null)
                    {
                        _exceptionLogger.LogInformation(eventId, detail.Message);
                    }
                    else
                    {
                        _exceptionLogger.LogInformation(eventId, ex, detail.Message);
                    }
                    break;

                case LogLevel.Warning:
                    if (ex == null)
                    {
                        _exceptionLogger.LogWarning(eventId, detail.Message);
                    }
                    else
                    {
                        _exceptionLogger.LogWarning(eventId, ex, detail.Message);
                    }
                    break;

                case LogLevel.Trace:
                    if (ex == null)
                    {
                        _exceptionLogger.LogTrace(eventId, detail.Message);
                    }
                    else
                    {
                        _exceptionLogger.LogTrace(eventId, ex, detail.Message);
                    }
                    break;

                case LogLevel.None:
                default:
                    break;
                }
            }
        }
コード例 #28
0
        /// <summary>
        /// Writes a log entry.
        /// </summary>
        /// <typeparam name="TState"></typeparam>
        /// <param name="logLevel">Entry will be written on this level.</param>
        /// <param name="eventId">Id of the event.</param>
        /// <param name="state">The entry to be written. Can be also an object.</param>
        /// <param name="exception">The exception related to this entry.</param>
        /// <param name="formatter">Function to create a <c>string</c> message of the <paramref name="state" /> and <paramref name="exception" />.</param>
        public void Log <TState>(
            mslogging.LogLevel logLevel
            , mslogging.EventId eventId
            , TState state
            , Exception exception
            , Func <TState, Exception, string> formatter
            )
        {
            if (!this.IsEnabled(logLevel))
            {
                return;
            }

            if (state == null && exception == null)
            {
                return;
            }

            // let's custom build the Data object that includes the exception
            // along with the current HTTP request context:

            string message = null;

            if (formatter != null)
            {
                message = formatter(state, exception);
            }

            Rollbar.DTOs.Body payloadBody = null;
            if (!string.IsNullOrWhiteSpace(message))
            {
                payloadBody = new DTOs.Body(new DTOs.Message(message));
            }
            else
            {
                payloadBody = new DTOs.Body(exception);
            }

            Dictionary <string, object> customProperties = new Dictionary <string, object>();

            customProperties.Add(
                "LogEventID"
                , $"{eventId.Id}" + (string.IsNullOrWhiteSpace(eventId.Name) ? string.Empty : $" ({eventId.Name})")
                );
            if (exception != null && message != null)
            {
                customProperties.Add("LogMessage", message);
            }

            var currentContext = GetCurrentContext();

            Dictionary <string, object> customRequestFields = null;

            if (currentContext != null)
            {
                customRequestFields = new Dictionary <string, object>();
                customRequestFields.Add("httpRequestTimestamp", currentContext.Timestamp);
                if (currentContext.HttpAttributes != null)
                {
                    customRequestFields.Add("httpRequestID", currentContext.HttpAttributes.RequestID);
                    customRequestFields.Add("statusCode", currentContext.HttpAttributes.StatusCode);
                    customRequestFields.Add("scheme", currentContext.HttpAttributes.Scheme);
                    customRequestFields.Add("protocol", currentContext.HttpAttributes.Protocol);
                }
            }

            var requestDto = new DTOs.Request(customRequestFields, currentContext?.HttpAttributes);

            DTOs.Data dataDto = new DTOs.Data(
                config: RollbarLocator.RollbarInstance.Config
                , body: payloadBody
                , custom: customProperties
                , request: requestDto
                )
            {
                Level = RollbarLogger.Convert(logLevel),
            };

            // log the Data object (the exception + the HTTP request data):
            RollbarLocator.RollbarInstance.Log(dataDto);
        }