Skip to content

Instantly share code, notes, and snippets.

@ArseniySavin
Created March 29, 2018 06:01
Show Gist options
  • Save ArseniySavin/38db49809ecfc4cfa26ec51ca73b1ae2 to your computer and use it in GitHub Desktop.
Save ArseniySavin/38db49809ecfc4cfa26ec51ca73b1ae2 to your computer and use it in GitHub Desktop.
LogScope
class Program
{
static void Main(string[] args)
{
using (var log = new LogScope())
{
try
{
var tM = new TestModel
{
Id = 100,
Name = "Test"
};
LogScope.EventLog.Debug<TestModel>(tM);
LogScope.EventLog.Information("Info!!!");
}
catch (Exception ex)
{
LogScope.EventLog.Error(ex.ToString());
LogScope.EventLog.Error<Exception>(ex);
}
}
}
}
public class LogScope : IDisposable
{
static ILogger _logger = null;
static Guid _activityId = default(Guid);
static string _callMemberName = string.Empty;
Configuration _logConfiguration = default(Configuration);
public ILogger Logger { get { return _logger; } private set { _logger = value; } }
public Guid ActivityId { get { return _activityId; } set { _activityId = value; } }
string LogPath {
get
{
if (_logConfiguration == null)
return string.Format(@"{0}\", Directory.GetCurrentDirectory());
else
return _logConfiguration.AppSettings.Settings["logger:log-path"].Value;
}
}
string LogFile
{
get
{
return _logConfiguration.AppSettings.Settings["logger:log-file-pattern"].Value
.FormatPlaceholder(Environment.UserName, DateTime.Now.ToString("yyyyMMddHHmm"), _activityId.ToString());
}
}
/// <summary>
/// The key for unique session identification
/// </summary>
/// <param name="activityId"></param>
public LogScope(Guid activityId)
: this(activityId, null)
{
}
/// <summary>
/// Whos call this method
/// </summary>
/// <param name="memberName"></param>
public LogScope(string memberName)
: this(default(Guid), memberName)
{
}
/// <summary>
/// Maine dot is for create instance
/// </summary>
/// <param name="activityId">The key for unique session identification</param>
/// <param name="memberName">Whos call this method</param>
public LogScope(Guid activityId = default(Guid), [CallerMemberName] string memberName = null)
{
if (_logger == null)
{
if (activityId == Guid.Empty)
{
_activityId = Guid.NewGuid();
Trace.CorrelationManager.ActivityId = _activityId;
}
//string logConfigurationPath = typeof(LogScope).Assembly.Location; //Directory.GetCurrentDirectory() + "\\" + typeof(LogScope).Assembly.ManifestModule.Name;
_logConfiguration = ConfigurationManager.OpenExeConfiguration(typeof(LogScope).Assembly.Location);
_logger = new LoggerConfiguration()
.ReadFrom.AppSettings(filePath: _logConfiguration.FilePath)
.Enrich.WithMachineName()
.Enrich.WithEnvironmentUserName()
//.WriteTo.RollingFile(new JsonFormatter(), logPath + "{Date}.log")
.WriteTo.File(new JsonFormatter(), LogPath + LogFile)
.CreateLogger();
Log.Logger = _logger;
this.Logger = _logger;
}
else
_activityId = Trace.CorrelationManager.ActivityId;
this.BeginScope(memberName);
}
/// <summary>
/// The write start scope
/// </summary>
/// <param name="name">whos call this method</param>
/// <returns></returns>
public LogScope BeginScope([CallerMemberName] string name = null)
{
_logger.Information("{Scope}, {Name}, {ActivityId}", "Start", name, _activityId);
return this;
}
/// <summary>
/// The write end scope
/// </summary>
/// <param name="name">who call this method</param>
/// <returns></returns>
public LogScope EndScope([CallerMemberName] string name = null)
{
_logger.Information("{Scope}, {Name}, {ActivityId}", "End", name, _activityId);
return this;
}
public void Dispose()
{
var callingMethod = new StackTrace(1, false).GetFrame(0).GetMethod();
EndScope(callingMethod.Name);
}
public class EventLog
{
public EventLog()
{
}
/// <summary>
/// Only using for class model
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="model">Model</param>
public static void Debug<T>(T model)
{
_logger.Debug<T>("{@Model}", model);
}
/// <summary>
/// Only using for string
/// </summary>
/// <param name="model">Model</param>
public static void Debug(string message)
{
_logger.Debug("{@Message}", message);
}
/// <summary>
/// Only for string
/// </summary>
/// <param name="message">message</param>
public static void Information(string message)
{
_logger.Information("{PayLoadMessage}", message);
}
/// <summary>
/// Only for string
/// </summary>
/// <param name="message">message</param>
public static void Error(string message)
{
_logger.Error("{PayLoadMessage}", message);
}
/// <summary>
/// Only using for Exception class
/// </summary>
///<typeparam name="T">Type</typeparam>
/// <param name="exception"></param>
public static void Error<T>(T exception)
{
_logger.Error("{@Exception}", exception);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment