Mate but I would just like to log an event. i.e without it being exception
So with the .net core Core event logging that uses CommonLogging.
I created a provider
So these logs can go to the coderr server.
_logger.LogInformation(LoggingEvents.ReStart, "Restart starting {now}", now);
And for different levels using the .net
_logger.LogInWarning(LoggingEvents.ReStart, "Restart starting {now}", now);
using Coderr.Client;
using Coderr.Client.Contracts;
using Coderr.Client.Reporters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace Transport.CTABS.Web.Startup
{
public class CodeRRLogger : ILogger
{
private readonly string _name;
private readonly CodeRRLoggerConfiguration _config;
public CodeRRLogger(string name, CodeRRLoggerConfiguration config)
{
_name = name;
_config = config;
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return logLevel == _config.LogLevel;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
if (_config.EventId == 0 || _config.EventId == eventId.Id)
{
//var color = Console.ForegroundColor;
//Console.ForegroundColor = _config.Color;
//Console.WriteLine($"{logLevel.ToString()} - {eventId.Id} - {_name} - {formatter(state, exception)}");
//Console.ForegroundColor = color;
}
//var ex = new Exception();
//ex.Data["ErrCollections"] = "MEX";
//var sut = new ErrorReporterContext(this, ex);
//Err.ReportLogicError(state.ToString());
ReportEvent(state.ToString());
}
public void ReportEvent(string errorMessage, object contextData = null, string errorId = null)
{
if (errorMessage == null) throw new ArgumentNullException(nameof(errorMessage));
var collections = new List<ContextCollectionDTO>();
if (contextData != null) AppendCustomContextData(contextData, collections);
collections.AddTag("logical-event"); //event
//var xx = new StackFrame(3).GetMethod();
//var yy = new StackFrame(2).GetMethod();
var method = new StackFrame(1).GetMethod();
//StackTrace st = new StackTrace(new StackFrame(1));
//Console.WriteLine(" Stack trace for next level frame: {0}",
// st.ToString());
//var x = st.ToString();
//Console.WriteLine(" Stack frame for next level: ");
//Console.WriteLine(" {0}", st.GetFrame(0).ToString());
//var y = st.GetFrame(0);
//Console.WriteLine(" Line Number: {0}",
// st.GetFrame(0).GetFileLineNumber().ToString());
var callerName = method.DeclaringType?.FullName + ":" + method.Name;
var trace = new StackTrace().ToString();
var pos = trace.IndexOf("\r\n", StringComparison.Ordinal);
if (pos == -1)
{
pos = trace.IndexOf("\n", StringComparison.Ordinal);
if (pos != -1) trace = trace.Remove(0, pos + 1);
}
else
{
trace = trace.Remove(0, pos + 2);
}
var logicException =
new LogicalErrorException(errorMessage, trace)
{
ErrorHashSource = errorId ?? $"{errorMessage}:{callerName}"
};
Err.Report(logicException, collections);
}
private void AppendCustomContextData(object contextData, IList<ContextCollectionDTO> contextInfo)
{
if (contextData is IEnumerable<ContextCollectionDTO> dtos)
{
var arr = dtos;
foreach (var dto in arr)
contextInfo.Add(dto);
}
else
{
var col = contextData.ToContextCollection();
contextInfo.Add(col);
}
}
}
}
With
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Transport.CTABS.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Transport.CTABS.Web.Startup
{
public class CodeRRLoggerConfiguration
{
private readonly IConfigurationRoot _appConfiguration;
private LogLevel _logLevel;
public CodeRRLoggerConfiguration(IHostingEnvironment env)
{
_appConfiguration = env.GetAppConfiguration();
_logLevel = _appConfiguration.GetValue<LogLevel>("AppSettings:LogLevel");
}
public LogLevel LogLevel { get { return _logLevel; } set { _logLevel = value; } }
public int EventId { get; set; } = 0;
//public ConsoleColor Color { get; set; } = ConsoleColor.Yellow;
}
}
and Provider is
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Transport.CTABS.Web.Startup
{
public class CodeRRLoggerProvider : ILoggerProvider
{
private readonly CodeRRLoggerConfiguration _config;
private readonly ConcurrentDictionary<string, CodeRRLogger> _loggers = new ConcurrentDictionary<string, CodeRRLogger>();
public CodeRRLoggerProvider(CodeRRLoggerConfiguration config)
{
_config = config;
}
public ILogger CreateLogger(string categoryName)
{
return _loggers.GetOrAdd(categoryName, name => new CodeRRLogger(name, _config));
}
public void Dispose()
{
_loggers.Clear();
}
}
}
So in Startup.Configure you just call
loggerFactory.AddProvider(new CodeRRLoggerProvider(new CodeRRLoggerConfiguration(env)));