Skip to content

Instantly share code, notes, and snippets.

@pedrovasconcellos
Created September 2, 2021 21:52
Show Gist options
  • Save pedrovasconcellos/c7e8eb94949cafe24fb8ddbc1de3d00c to your computer and use it in GitHub Desktop.
Save pedrovasconcellos/c7e8eb94949cafe24fb8ddbc1de3d00c to your computer and use it in GitHub Desktop.
LogEntity
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
namespace Vasconcellos.Log
{
public class LogEntity
{
[JsonConverter(typeof(JsonStringEnumConverter))]
public LogLevel LogLevel { get; private set; }
public DateTime Created { get; private set; }
public string Message { get; private set; }
public string ClassName { get; private set; }
public string MethodName { get; private set; }
public string CorrelationId { get; private set; }
public string ClientId { get; private set; }
public IDictionary<string, dynamic> ValueDictionary { get; private set; }
public static LogEntity Create(LogLevel logLevel)
{
var logEntity = new LogEntity
{
ValueDictionary = new Dictionary<string, dynamic>()
};
logEntity.Created = DateTime.UtcNow;
logEntity.LogLevel = logLevel;
return logEntity;
}
public LogEntity WithMessage(string message)
{
this.Message = message;
return this;
}
public LogEntity WithClassName(Type classType)
{
this.ClassName = classType.FullName;
return this;
}
public LogEntity WithMethodName(string methodName)
{
this.MethodName = methodName;
return this;
}
public LogEntity WithCorrelationId(string correlationId)
{
this.CorrelationId = correlationId;
return this;
}
public LogEntity WithClientId(string clientId)
{
this.ClientId = clientId;
return this;
}
private LogEntity WithValueDictionary(string key, dynamic value)
{
this.ValueDictionary = new Dictionary<string, dynamic>()
{
{ key, value }
};
return this;
}
public LogEntity WithValueDictionaryItemWithMinifiedString<T>(string key, T value, int maxLength = 50)
where T : new()
{
var copyByValue = value == null
? default : this.GetCopyForValue(value);
try
{
this.MinifiedString(copyByValue, maxLength);
}
catch (Exception ex)
{
var messageError = ex.Message;
this.AddValueDictonary("ErrorMinifiedStringObject.Message", messageError);
}
this.AddValueDictonary(key, copyByValue);
return this;
}
public LogEntity WithValueDictionaryItemWithMinifiedString(string key, string value, int maxLength = 400)
{
var minifiedValue = this.GetSubString(value, maxLength);
this.AddValueDictonary(key, minifiedValue);
return this;
}
public LogEntity WithValueDictionaryItemWithMinifiedString(string key, List<string> listValue, int maxLength = 150)
{
var listMinifiedValues = this.GetSubStringList(listValue, maxLength);
this.AddValueDictonary(key, listMinifiedValues);
return this;
}
public LogEntity WithValueDictionaryItem(string key, dynamic value)
{
this.AddValueDictonary(key, value);
return this;
}
private void AddValueDictonary(string key, dynamic value)
{
if (this.ValueDictionary != default)
this.ValueDictionary.Add(key, value);
else
this.WithValueDictionary(key, value);
return;
}
private T GetCopyForValue<T>(T obj)
{
JsonSerializerOptions options = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
var json = JsonSerializer.Serialize(obj, options);
var objectResult = JsonSerializer.Deserialize<T>(json);
return objectResult;
}
private string GetSubString(string value, int maxLength)
{
var minifiedValue = !string.IsNullOrEmpty(value) && value.Length > maxLength
? value?.Substring(0, maxLength)
: value;
return minifiedValue;
}
private List<string> GetSubStringList(IEnumerable<string> listValue, int maxLength)
{
if (listValue == default)
return default;
var listMinifiedValues = new List<string>();
foreach (var value in listValue)
{
var minifiedValue = this.GetSubString(value, maxLength);
listMinifiedValues.Add(minifiedValue);
}
return listMinifiedValues;
}
private bool ShouldMinifiedString<T>(T obj)
{
if (obj == null
|| obj is DateTime
|| obj is Guid
|| obj is string
|| obj is IEnumerable<string>
|| obj is IEnumerable<short>
|| obj is IEnumerable<int>
|| obj is IEnumerable<long>
|| obj is IEnumerable<bool>
|| obj is IEnumerable<double>
|| obj is IEnumerable<decimal>
|| obj is IEnumerable<DateTime>
|| obj is IEnumerable<Guid>
|| !(obj is object)
|| obj.GetType().IsPrimitive
|| obj.GetType().IsEnum
|| obj is IDictionary)
return false;
else
return true;
}
private void MinifiedString<T>(T obj, int maxLength)
where T : new()
{
if (!this.ShouldMinifiedString(obj))
return;
if (obj is IEnumerable<object>)
{
foreach (var itemObj in obj as IEnumerable<object>)
{
this.MinifiedString(itemObj, maxLength);
}
return;
}
var propertyInfos = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var propertyInfo in propertyInfos)
{
var value = GetPropertyValue(obj, propertyInfo.Name);
if (value == null || value is DateTime || value is Guid
|| value is IEnumerable<DateTime> || value is IEnumerable<Guid>
|| value.GetType().IsPrimitive || obj.GetType().IsEnum || value is IDictionary)
continue;
else if (value is string)
{
value = this.GetSubString(value?.ToString(), maxLength);
propertyInfo.SetValue(obj, value);
}
else if (value is IEnumerable<string>)
{
value = this.GetSubStringList(value as IEnumerable<string>, maxLength);
propertyInfo.SetValue(obj, value);
}
else if (value is object)
{
this.MinifiedString(value, maxLength);
}
else if (value is IEnumerable<object>)
{
foreach (var itemValue in value as IEnumerable<object>)
{
this.MinifiedString(itemValue, maxLength);
}
}
}
}
private object GetPropertyValue(object src, string propName)
{
if (src == null)
return null;
if (propName == null)
return null;
if (propName.Contains("."))//complex type nested
{
var temp = propName.Split(new char[] { '.' }, 2);
return GetPropertyValue(GetPropertyValue(src, temp[0]), temp[1]);
}
else
{
var prop = src.GetType().GetProperty(propName);
return prop != null ? prop.GetValue(src, null) : null;
}
}
public string GetJson()
{
JsonSerializerOptions options = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
return JsonSerializer.Serialize(this, options);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment