Skip to content

Commit

Permalink
Merge pull request #64 from amccool/logerror-message
Browse files Browse the repository at this point in the history
dont overwrite the logger message with the exception.message
  • Loading branch information
amccool committed Nov 30, 2021
2 parents e7ad0c0 + 04407a0 commit 0ebb933
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 95 deletions.
7 changes: 4 additions & 3 deletions example/SampleApp/App.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,10 @@ public async Task Run()
_logger.LogWarning("Run...................");
}

_logger.LogInformation($"Ending Service for with LogKey {logKey}");
_logger.LogInformation("Ending Service for with LogKey {logKey}", logKey);
}

private async Task Breakstuff()
private Task Breakstuff()
{
int x = 0;
try
Expand All @@ -64,8 +64,9 @@ private async Task Breakstuff()
}
catch (Exception e)
{
_logger.LogError(100, e, "sdgsgsgsg", 1, "3");
_logger.LogError(100, e, "sdgsgsgsg {a} {b}", 1, "sdfsdgfsg");
}
return Task.CompletedTask;
}
}
}
13 changes: 11 additions & 2 deletions example/SampleApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,7 @@ public Program()
.AddElasticSearch(options =>
{
//options.ElasticsearchEndpoint = new Uri(@"http://localhost:9200/");
//options.ElasticsearchEndpoint = new Uri(@"https://elasticsearch.mgmc.rauland/");
options.ElasticsearchEndpoint = new Uri(@"http://es.devint.dev-r5ead.net:9200/");
//options.IndexName = "trace";
});
});

Expand Down Expand Up @@ -78,6 +76,17 @@ public void Runner(string[] args)
logger.LogTrace("Starting application");
logger.LogWarning("Starting application");

try
{
int x = 0;
var y = 100 / x;
}
catch (Exception ex)
{
logger.LogCritical(new EventId(10, "cccc"), ex, "blah blah {junk}", 19999999);
//throw;
}


//do the actual work here
var bar = _serviceProvider.GetService<IApp>();
Expand Down
3 changes: 0 additions & 3 deletions src/ElasticLogger.Test/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,6 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerF
await next.Invoke();
});

//app.UseMvcWithDefaultRoute();
//app.useco .AddControllers
}
}
}
90 changes: 6 additions & 84 deletions src/ElasticSearch.Extensions.Logging/ElasticSearchLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@

namespace AM.Extensions.Logging.ElasticSearch
{
public class ElasticsearchLogger : ILogger
internal sealed class ElasticsearchLogger : ILogger
{

private readonly LogLevel _logLevel;
private readonly string _userDomainName;
private readonly string _userName;
Expand All @@ -32,27 +31,9 @@ public ElasticsearchLogger(string categoryName, Action<JObject> scribeProcessor)
_userDomainName = Environment.UserDomainName;
_userName = Environment.UserName;
_machineName = Environment.MachineName;

}

//public ElasticsearchLogger(string categoryName, Uri endpoint, string indexPrefix)
//{
// Name = categoryName;

// _endpoint = endpoint;
// _indexPrefix = indexPrefix;

// // Default is to turn on all the logging
// _logLevel = LogLevel.Trace;

// _userDomainName = Environment.UserDomainName;
// _userName = Environment.UserName;
// _machineName = Environment.MachineName;
// Initialize();
//}

public string Name { get; }



public IDisposable BeginScope<TState>(TState state)
Expand Down Expand Up @@ -90,80 +71,22 @@ public void Log<TState>(LogLevel logLevel, EventId eventId,
WriteTrace(Name, logLevel, eventId.Id, message, Guid.Empty, exception);
}

protected void WriteTrace(
private void WriteTrace(
string loggerName,
LogLevel eventType,
int id,
string message,
Guid? relatedActivityId,
object data)
Exception data)
{
string updatedMessage = message;
JObject payload = null;
var serializerIgnoreReferenceLoop = new JsonSerializer { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
if (data != null)
{
if (data is Exception)
{
updatedMessage = ((Exception)data).Message;

payload = JObject.FromObject(data, serializerIgnoreReferenceLoop);
}
else if (data is XPathNavigator)
{
var xdata = data as XPathNavigator;
//xdata.MoveToRoot();

XDocument xmlDoc;
try
{
xmlDoc = XDocument.Parse(xdata.OuterXml);

}
catch (Exception)
{
xmlDoc = XDocument.Parse(xdata.ToString());
//eat
//throw;
}

// Convert the XML document in to a dynamic C# object.
dynamic xmlContent = new ExpandoObject();
ExpandoObjectHelper.Parse(xmlContent, xmlDoc.Root);

string json = JsonConvert.SerializeObject(xmlContent, new JsonSerializerSettings{ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
payload = JObject.Parse(json);
}
else if (data is DateTime)
{
payload = new JObject();
payload.Add("System.DateTime", (DateTime)data);
}
else if (data is string)
{
payload = new JObject();
payload.Add("string", (string)data);
}
else if (data.GetType().IsValueType)
{
payload = new JObject { { "data", data.ToString() } };
}
else
{
try
{
payload = JObject.FromObject(data, serializerIgnoreReferenceLoop);
}
catch (JsonSerializationException jEx)
{
payload = new JObject();
payload.Add("FAILURE", jEx.Message);
payload.Add("data", data.GetType().ToString());
}
}
payload = JObject.FromObject(data, serializerIgnoreReferenceLoop);
}

InternalWrite(new TraceEventCache(), loggerName, eventType, id, updatedMessage, relatedActivityId, payload);
InternalWrite(new TraceEventCache(), loggerName, eventType, id, message, relatedActivityId, payload);
}

private void InternalWrite(
Expand All @@ -172,8 +95,7 @@ private void InternalWrite(
LogLevel eventType,
int? traceId,
string message,
Guid?
relatedActivityId,
Guid? relatedActivityId,
JObject dataObject)
{
DateTime logTime;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,10 @@ private async Task WriteDirectlyToES(JObject jo)
//POST /_bulk? filter_path = items.*.error
private static Dictionary<string, object> filter_path = new Dictionary<string, object>() { { "filter_path", "items.*.error" } };

private async Task WriteDirectlyToESAsBatch(IEnumerable<JObject> jos)
private Task WriteDirectlyToESAsBatch(IEnumerable<JObject> jos)
{
if (!jos.Any())
return;
return Task.CompletedTask;

var indx = new { index = new { _index = Index, _type = DocumentType } };
var indxC = Enumerable.Repeat(indx, jos.Count());
Expand All @@ -156,11 +156,12 @@ private async Task WriteDirectlyToESAsBatch(IEnumerable<JObject> jos)
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Current);

return Task.CompletedTask;
}

private void WriteToQueueForProcessing(JObject jo)
{
this._queueToBePosted.Add(jo);
_queueToBePosted.Add(jo);
}

#region IDisposable Support
Expand All @@ -173,6 +174,8 @@ protected virtual void Dispose(bool disposing)
if (disposing)
{
// TODO: dispose managed state (managed objects).
//_client.
_queueToBePosted.Dispose();
}

// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
Expand Down

0 comments on commit 0ebb933

Please sign in to comment.