Ejemplo n.º 1
0
        public void Log(Microsoft.Extensions.Logging.LogLevel logLevel, int eventId, object state, Exception exception, Func <object, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }
            var message = string.Empty;
            var values  = state as ILogValues;

            if (formatter != null)
            {
                message = formatter(state, exception);
            }
            else
            {
                message = LogFormatter.Formatter(state, exception);
            }
            if (string.IsNullOrEmpty(message))
            {
                return;
            }



            lock (_lock)
            {
                var str = string.Format("{0:yyyy-MM-dd HH:mm:ss} ", DateTime.Now) + _logLevelMappings[logLevel] + ": " + message;
                writeToLog(str);
            }
        }
Ejemplo n.º 2
0
            public void Log(
                LogLevel logLevel,
                int eventId,
                object state,
                Exception exception,
                Func <object, Exception, string> formatter)
            {
                var nLogLogLevel = GetLogLevel(logLevel);
                var message      = string.Empty;

                if (formatter != null)
                {
                    message = formatter(state, exception);
                }
                else
                {
                    message = LogFormatter.Formatter(state, exception);
                }
                if (!string.IsNullOrEmpty(message))
                {
                    var eventInfo = LogEventInfo.Create(nLogLogLevel, _logger.Name, message, exception);
                    eventInfo.Properties["EventId"] = eventId;
                    _logger.Log(eventInfo);
                }
            }
Ejemplo n.º 3
0
        /// <inheritdoc />
        public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func <object, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            string message;
            var    values = state as ILogValues;

            if (formatter != null)
            {
                message = formatter(state, exception);
            }
            else if (values != null)
            {
                message = LogFormatter.FormatLogValues(values);
                if (exception != null)
                {
                    message += Environment.NewLine + exception;
                }
            }
            else
            {
                message = LogFormatter.Formatter(state, exception);
            }

            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            message = $"{ logLevel }: {message}";
            DebugWriteLine(message, _name);
        }
Ejemplo n.º 4
0
        public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func <object, Exception, string> formatter)
        {
            string     message = string.Empty;
            ILogValues values  = state as ILogValues;

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

            //    message = $"{ logLevel.ToString() } ({eventId}): {exception?.ToString()}";

            //    if (exception != null)
            //    {
            //        message += Environment.NewLine + exception;
            //    }
            //}
            else
            {
                message = LogFormatter.Formatter(state, exception);
            }

            LogDataQueue.Enqueue(message);
        }
        public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func <object, Exception, string> formatter)
        {
            var level = ConvertLevel(logLevel);

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

            var    logger          = _logger;
            string messageTemplate = null;

            var structure = state as ILogValues;

            if (structure != null)
            {
                foreach (var property in structure.GetValues())
                {
                    if (property.Key == SerilogLoggerProvider.OriginalFormatPropertyName && property.Value is string)
                    {
                        messageTemplate = (string)property.Value;
                    }
                    else if (property.Key.StartsWith("@"))
                    {
                        logger = logger.ForContext(property.Key.Substring(1), property.Value, destructureObjects: true);
                    }
                    else
                    {
                        logger = logger.ForContext(property.Key, property.Value);
                    }
                }

                var stateType     = state.GetType();
                var stateTypeInfo = stateType.GetTypeInfo();
                // Imperfect, but at least eliminates `1 and + names
                if (messageTemplate == null && !stateTypeInfo.IsGenericType && !stateTypeInfo.IsNested)
                {
                    messageTemplate = "{" + stateType.Name + ":l}";
                    logger          = logger.ForContext(stateType.Name, LogFormatter.Formatter(state, null));
                }
            }

            if (messageTemplate == null && state != null)
            {
                messageTemplate = LogFormatter.Formatter(state, null);
            }

            if (string.IsNullOrEmpty(messageTemplate))
            {
                return;
            }

            if (eventId != 0)
            {
                logger = logger.ForContext("EventId", eventId);
            }

            logger.Write(level, exception, messageTemplate);
        }
Ejemplo n.º 6
0
        public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func <object, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }
            var message = string.Empty;
            var values  = state as ILogValues;

            if (formatter != null)
            {
                message = formatter(state, exception);
            }
            else if (values != null)
            {
                var builder = new StringBuilder();
                FormatLogValues(
                    builder,
                    values,
                    level: 1,
                    bullet: false);
                message = builder.ToString();
                if (exception != null)
                {
                    message += Environment.NewLine + exception;
                }
            }
            else
            {
                message = LogFormatter.Formatter(state, exception);
            }
            if (string.IsNullOrEmpty(message))
            {
                return;
            }
            lock (_lock)
            {
                var originalForegroundColor = Console.ForegroundColor;  // save current colors
                var originalBackgroundColor = Console.BackgroundColor;
                SetConsoleColor(logLevel);
                try
                {
                    Console.WriteLine(FormatMessage(logLevel, message));
                }
                finally
                {
                    Console.ForegroundColor = originalForegroundColor;  // reset initial colors
                    Console.BackgroundColor = originalBackgroundColor;
                }
            }
        }
        public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func <object, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }
            string message = null;

            if (null != formatter)
            {
                message = formatter(state, exception);
            }
            else
            {
                message = LogFormatter.Formatter(state, exception);
            }
            switch (logLevel)
            {
            case LogLevel.Verbose:
            case LogLevel.Debug:
                _logger.Debug(message, exception);
                break;

            case LogLevel.Information:
                _logger.Info(message, exception);
                break;

            case LogLevel.Warning:
                _logger.Warn(message, exception);
                break;

            case LogLevel.Error:
                _logger.Error(message, exception);
                break;

            case LogLevel.Critical:
                _logger.Fatal(message, exception);
                break;

            default:
                _logger.Warn($"Encountered unknown log level {logLevel}, writing out as Info.");
                _logger.Info(message, exception);
                break;
            }
        }
Ejemplo n.º 8
0
        /// <inheritdoc />
        public void Log(
            LogLevel logLevel,
            int eventId,
            object state,
            Exception exception,
            Func <object, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            string message;
            var    values = state as ILogValues;

            if (formatter != null)
            {
                message = formatter(state, exception);
            }
            else if (values != null)
            {
                message = LogFormatter.FormatLogValues(values);
                if (exception != null)
                {
                    message += Environment.NewLine + exception;
                }
            }
            else
            {
                message = LogFormatter.Formatter(state, exception);
            }

            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            message = _name + Environment.NewLine + message;

            // category '0' translates to 'None' in event log
            _eventLog.WriteEntry(message, GetEventLogEntryType(logLevel), eventId, category: 0);
        }
Ejemplo n.º 9
0
        public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func <object, Exception, string> formatter)
        {
            var level = ConvertLevel(logLevel);

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

            var logger = _logger;

            var message = string.Empty;

            if (formatter != null)
            {
                message = formatter(state, exception);
            }
            else
            {
                message = LogFormatter.Formatter(state, exception);
            }
            if (string.IsNullOrEmpty(message))
            {
                return;
            }
            if (eventId != 0)
            {
                logger = logger.ForContext("EventId", eventId, false);
            }
            var structure = state as ILogValues;

            if (structure != null)
            {
                logger = logger.ForContext(new[] { new StructureEnricher(structure) });
            }
            if (exception != null)
            {
                logger = logger.ForContext(new[] { new ExceptionEnricher(exception) });
            }

            logger.Write(level, "{Message:l}", message);
        }
Ejemplo n.º 10
0
    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
        if (!IsEnabled(logLevel))
        {
            return;
        }

        if (formatter != null)
        {
            message = formatter(state, exception);
        }
        else
        {
            message = LogFormatter.Formatter(state, exception);
        }

        switch (logLevel)
        {
            case LogLevel.Critical:
                _log.Fatal(state, exception);
                break;
            case LogLevel.Debug:
            case LogLevel.Trace:
                _log.Debug(state, exception);
                break;      
            case LogLevel.Error:
                _log.Error(state, exception);
                break;
            case LogLevel.Information:
                _log.Info(state, exception);
                break;
            case LogLevel.Warning:
                _log.Warn(state, exception);
                break;
            default:
                _log.Warn($"Encountered unknown log level {logLevel}, writing out as Info.");
                _log.Info(state, exception);
                break;
        }
}
Ejemplo n.º 11
0
        public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func <object, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }
            var message = string.Empty;
            var values  = state as ILogValues;

            if (formatter != null)
            {
                message = formatter(state, exception);
            }
            else if (values != null)
            {
                var builder = new StringBuilder();
                FormatLogValues(
                    builder,
                    values,
                    level: 1,
                    bullet: false);
                message = builder.ToString();
                if (exception != null)
                {
                    message += Environment.NewLine + exception;
                }
            }
            else
            {
                message = LogFormatter.Formatter(state, exception);
            }
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            WriteMessage(logLevel, Name, eventId, message);
        }
Ejemplo n.º 12
0
        public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func <object, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }
            var message = string.Empty;
            var values  = state as ILogValues;

            if (formatter != null)
            {
                message = formatter(state, exception);
            }
            else if (values != null)
            {
                var builder = new StringBuilder();
                FormatLogValues(
                    builder,
                    values,
                    level: 1,
                    bullet: false);
                message = builder.ToString();
                if (exception != null)
                {
                    message += Environment.NewLine + exception;
                }
            }
            else
            {
                message = LogFormatter.Formatter(state, exception);
            }
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            var log = new TLog
            {
                Message = Trim(message, EntityFrameworkLog.MaximumMessageLength),
                Date    = DateTime.UtcNow,
                Level   = logLevel.ToString(),
                Logger  = _name,
                Thread  = eventId.ToString()
            };

            if (exception != null)
            {
                log.Exception = Trim(exception.ToString(), EntityFrameworkLog.MaximumExceptionLength);
            }

            var httpContext = _services.GetRequiredService <IHttpContextAccessor>()?.HttpContext;

            if (httpContext != null)
            {
                log.Browser  = httpContext.Request.Headers["User-Agent"];
                log.Username = httpContext.User.Identity.Name;
                try { log.HostAddress = httpContext.Connection.LocalIpAddress?.ToString(); }
                catch (ObjectDisposedException) { log.HostAddress = "Disposed"; }
                log.Url = httpContext.Request.Path;
            }

            var db = _services.GetRequiredService <TDbContext>();

            //db.Set<EntityFrameworkLog>().Add(log);
            //db.Set<EntityFrameworkLog>();
            //_context.EntityFrameworkLog.Add(log);

            db.Set <TLog>().Add(log);

            try
            {
                db.SaveChanges();
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.Message);
            }
        }
Ejemplo n.º 13
0
        public void Log(
            LogLevel logLevel,
            int eventId,
            object state,
            Exception exception,
            Func <object, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }
            var message = string.Empty;
            var values  = state as ILogValues;

            if (formatter != null)
            {
                message = formatter(state, exception);
            }
            else if (values != null)
            {
                var builder = new StringBuilder();
                FormatLogValues(
                    builder,
                    values,
                    level: 1,
                    bullet: false);

                message = builder.ToString();
                if (exception != null)
                {
                    message += Environment.NewLine + exception;
                }
            }
            else
            {
                message = LogFormatter.Formatter(state, exception);
            }
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            contextAccessor = services.GetService <IHttpContextAccessor>();

            string ipAddress = GetIpAddress();
            string culture   = CultureInfo.CurrentCulture.Name;
            string url       = GetRequestUrl();
            string shortUrl  = GetShortUrl(url);
            string thread    = System.Threading.Thread.CurrentThread.Name + " " + eventId.ToString();
            string logLev    = logLevel.ToString();

            // an exception is expected here if the db has not yet been populated
            // or if the db is not accessible
            // we cannot allow logging to raise exceptions
            // so we must swallow any exception here
            // would be good if we could only swallow specific exceptions
            try
            {
                logRepo.AddLogItem(
                    DateTime.UtcNow,
                    ipAddress,
                    culture,
                    url,
                    shortUrl,
                    thread,
                    logLev,
                    logger,
                    message);
            }
            catch
            { }
        }
Ejemplo n.º 14
0
        public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func <object, Exception, string> formatter)
        {
            var level = ConvertLevel(logLevel);

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

            var    logger          = _logger;
            string messageTemplate = null;
            var    format          = formatter ?? ((s, _) => LogFormatter.Formatter(s, null));

            var structure = state as ILogValues;

            if (structure != null)
            {
                foreach (var property in structure.GetValues())
                {
                    if (property.Key == SerilogLoggerProvider.OriginalFormatPropertyName && property.Value is string)
                    {
                        messageTemplate = (string)property.Value;
                    }
                    else if (property.Key.StartsWith("@"))
                    {
                        logger = logger.ForContext(property.Key.Substring(1), property.Value, destructureObjects: true);
                    }
                    else
                    {
                        logger = logger.ForContext(property.Key, property.Value);
                    }
                }

                var stateType     = state.GetType();
                var stateTypeInfo = stateType.GetTypeInfo();
                // Imperfect, but at least eliminates `1 names
                if (messageTemplate == null && !stateTypeInfo.IsGenericType)
                {
                    messageTemplate = "{" + stateType.Name + ":l}";
                    logger          = logger.ForContext(stateType.Name, format(state, null));
                }
            }

            if (messageTemplate == null && state != null)
            {
                messageTemplate = "{State:l}";
                logger          = logger.ForContext("State", format(state, null));
            }

            if (string.IsNullOrEmpty(messageTemplate))
            {
                return;
            }

            if (eventId != 0)
            {
                logger = logger.ForContext("EventId", eventId);
            }

            var parsedTemplate = _messageTemplateParser.Parse(messageTemplate);
            var evt            = new LogEvent(DateTimeOffset.Now, level, exception, parsedTemplate, Enumerable.Empty <LogEventProperty>());

            logger.Write(evt);
        }