Last active
May 23, 2016 09:18
-
-
Save mkropat/efa2b76272f900774f27 to your computer and use it in GitHub Desktop.
C# logging micro-framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class MicroLog | |
{ | |
public static void Write(params object[] objs) | |
{ | |
var logName = typeof(MicroLog).Assembly.GetName().Name + ".debug.log"; | |
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); | |
var logPath = System.IO.Path.Combine(documentsPath, logName); | |
var timestamp = DateTime.Now.ToString("HH:mm:ss.fff"); | |
var asStrings = Array.ConvertAll<object, string>(objs, Format); | |
var line = string.Format("{0}: {1}", timestamp, string.Join(" - ", asStrings)); | |
System.IO.File.AppendAllLines(logPath, new[] { line }); | |
} | |
private static string Format(object obj) | |
{ | |
return Format(obj, 1); | |
} | |
private static string Format(object obj, int indent) | |
{ | |
if (obj == null) | |
return "null"; | |
else if (obj is string || obj.GetType().IsValueType) | |
return Convert.ToString(obj); | |
else if (obj is System.Collections.IEnumerable) | |
return FormatEnumerable((System.Collections.IEnumerable)obj, indent); | |
else if (indent > 1) | |
return Convert.ToString(obj); | |
else | |
return FormatObject(obj, indent); | |
} | |
private static string FormatObject(object obj, int indent) | |
{ | |
var properties = new List<string>(); | |
var publicInstance = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance; | |
foreach (var m in obj.GetType().GetMembers(publicInstance)) | |
{ | |
var p = m as System.Reflection.PropertyInfo; | |
if (p != null) | |
properties.Add(string.Format("{0}: {1}", m.Name, Format(p.GetValue(obj), indent + 1))); | |
} | |
return FormatDataStructure(obj, properties.ToArray(), indent); | |
} | |
private static string FormatEnumerable(System.Collections.IEnumerable enumerable, int indent) | |
{ | |
var items = new List<string>(); | |
foreach (var item in enumerable) | |
items.Add(Format(item, indent + 1)); | |
return FormatDataStructure(enumerable, items.ToArray(), indent); | |
} | |
private static string FormatDataStructure(object obj, string[] properties, int indentLevel) | |
{ | |
var innerIndent = new string(' ', indentLevel * 2); | |
var outerIndent = new string(' ', (indentLevel - 1) * 2); | |
return obj.GetType().Name + " {" + Environment.NewLine + | |
innerIndent + string.Join(Environment.NewLine + innerIndent, properties) + Environment.NewLine + | |
outerIndent + "}"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment