public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { try { using (LoggingContext db = new LoggingContext(dbContextOptions)) { LogEntry entry = new LogEntry(); entry.Level = logLevel; entry.Category = categoryName; entry.EventID = eventId.Id; entry.Message = formatter(state, exception); Exception ex = exception; for (int i = 0; ex != null; i++) { LogException logException = new LogException(); logException.Order = i; logException.Type = ex.GetType().FullName; logException.Message = ex.Message; logException.StackTrace = ex.StackTrace; logException.Source = ex.Source; logException.HelpLink = ex.HelpLink; entry.Exceptions.Add(logException); ex = ex.InnerException; } db.Add(entry); db.SaveChanges(); } } catch (Exception ex) { Console.WriteLine($"{DateTime.Now} - ERROR: Failed to add log entry to database. ({ex.GetType().FullName}: {ex.Message})"); } }
/// <summary>Writes a log entry.</summary> /// <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>( 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)); } var message = formatter(state, exception); if (string.IsNullOrEmpty(message)) { return; } if (exception != null) { message += Environment.NewLine + exception; } LogEntry eventLog = new LogEntry { Message = message, EventId = eventId.Id, LogLevel = logLevel.ToString(), DateCreated = DateTime.UtcNow, DateModified = DateTime.UtcNow }; _context.Add(eventLog); _context.SaveChanges(); }