Esempio n. 1
0
        public static KafkaLoggerError Parse(Exception exception)
        {
            if (exception == null)
            {
                return(null);
            }

            var error = new KafkaLoggerError()
            {
                Message    = exception.Message,
                StackTrace = exception.StackTrace,
                InnerError = Parse(exception.InnerException)
            };

            List <KafkaLoggerError> list = new List <KafkaLoggerError>();

            if (exception is AggregateException aggregateException)
            {
                foreach (var ex in aggregateException.InnerExceptions)
                {
                    list.Add(Parse(ex));
                }
            }
            error.InnerErrors = list.ToArray();

            return(error);
        }
Esempio n. 2
0
        /// <summary>
        /// 日志记录
        /// </summary>
        /// <typeparam name="TState"></typeparam>
        /// <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 (string.IsNullOrEmpty(ip))
            {
                lock (ip)
                {
                    if (string.IsNullOrEmpty(ip))
                    {
                        ip = GetLocalIp();
                    }
                }
            }

            if (IsEnabled(logLevel))
            {
                try
                {
                    var message = new KafkaLoggerMessage <TState>
                    {
                        Category        = category,
                        Error           = KafkaLoggerError.Parse(exception),
                        LogLevel        = logLevel,
                        State           = state,
                        Message         = formatter?.Invoke(state, exception),
                        ApplicationName = loggerOptions.ApplicationName,
                        Time            = DateTime.Now,
                        IpAddress       = ip,
                    };
                    //发送消息
                    producer.Publish(new KafkaMessage()
                    {
                        Key       = string.IsNullOrEmpty(loggerOptions.Key) ? category : loggerOptions.Key,
                        Partition = loggerOptions.Partition,
                        Message   = message
                    });
                }
                catch (Exception ex)
                {
                    do
                    {
                        Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
                    } while ((ex = ex.InnerException) != null);
                };
            }
        }