using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace Tango.Logging
{
///
/// Represents a base class for log items.
///
[Serializable]
public abstract class LogItemBase : INotifyPropertyChanged
{
private static String base_path;
[NonSerialized]
private Object _logObject;
///
/// Gets or sets an optional log object.
///
[JsonIgnore]
public Object LogObject
{
get { return _logObject; }
set { _logObject = value; }
}
///
/// Gets or sets the caller method adding the exception.
///
public String CallerMethodName { get; set; }
///
/// Gets or sets the caller file.
///
public String CallerFile { get; set; }
///
/// Gets the relative caller file.
///
[JsonIgnore]
public String RelativeCallerFile
{
get { return GetRelativeCallerFilePath(); }
}
///
/// Gets the name of the caller file class.
///
public String ClassName
{
get { return RelativeCallerFile.Split('\\').LastOrDefault()?.Split('.').FirstOrDefault(); }
}
///
/// Gets or sets the caller line number.
///
public int CallerLineNumber { get; set; }
///
/// Gets or sets the DateTime for the log.
///
public DateTime TimeStamp { get; set; }
///
/// Gets or sets the log category.
///
public LogCategory Category { get; set; }
///
/// Gets the log message.
///
public abstract String Message { get; set; }
///
/// Returns a formatted string of the log item.
///
public abstract override String ToString();
///
/// Gets the relative caller file path.
///
///
protected virtual String GetRelativeCallerFilePath()
{
if (base_path == null)
{
int index = CallerFile.IndexOf("Visual_Studio") + "Visual_Studio".Length + 1;
String relative = CallerFile.Substring(index, CallerFile.Length - index);
base_path = CallerFile.Replace(relative, "");
}
if (Path.IsPathRooted(CallerFile))
{
return CallerFile.Remove(0, base_path.Length);
}
else
{
return CallerFile;
}
}
///
/// Serializes this log item using .
///
///
public byte[] Serialize()
{
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter f = new BinaryFormatter();
f.Serialize(ms, this);
return ms.ToArray();
}
}
///
/// Deserializes the specified data using to create a log item.
///
/// The data.
///
public static LogItemBase Deserialize(byte[] data)
{
using (MemoryStream ms = new MemoryStream(data))
{
ms.Position = 0;
BinaryFormatter f = new BinaryFormatter();
return f.Deserialize(ms) as LogItemBase;
}
}
///
/// Raises the property changed event.
///
/// Name of the property.
protected virtual void RaisePropertyChanged(String propName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
///
/// Occurs when a property value changes.
///
public event PropertyChangedEventHandler PropertyChanged;
}
}