Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class ObjectLogger
- {
- public static void LogObjectContent(this object model)
- {
- try
- {
- SaveObjectToFile(model.GetLogFor());
- }
- catch (Exception e)
- {
- Console.WriteLine(e);
- throw;
- }
- }
- private static string GetLogFor(this object target)
- {
- var properties =
- from property in target.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
- select new
- {
- Name = property.Name,
- Value = property.GetValue(target, null)
- };
- var builder = new StringBuilder();
- foreach (var property in properties)
- {
- builder
- .Append(property.Name)
- .Append(" = ")
- .Append(property.Value)
- .AppendLine();
- }
- return builder.ToString();
- }
- private static void SaveObjectToFile(string content)
- {
- string path = HostingEnvironment.MapPath(Path.Combine("~/RequestLogs/" + GetFileName()).Trim());
- if (!File.Exists(path))
- {
- // Create a file to write to.
- using (StreamWriter sw = File.CreateText(path))
- {
- sw.WriteLine(content);
- }
- }
- }
- private static string GetFileName()
- {
- var dateNow = DateTime.Now;
- return (dateNow.Day + "꞉"
- + dateNow.Month + "꞉"
- + dateNow.Year + "꞉"
- + "__" //to separate date and hours
- + DateTime.Now.Hour + "꞉"
- + DateTime.Now.Minute + "꞉"
- + DateTime.Now.Second + "꞉"
- + DateTime.Now.Millisecond
- + ".txt")
- .ToSafeFileName();
- }
- private static string ToSafeFileName(this string s)
- {
- return s
- .Replace("\\", "")
- .Replace("/", "")
- .Replace("\"", "")
- .Replace("*", "")
- .Replace(":", "")
- .Replace("?", "")
- .Replace("<", "")
- .Replace(">", "")
- .Replace("|", "");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement