forked from CosmosOS/Cosmos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLogUtility.cs
76 lines (68 loc) · 2.3 KB
/
LogUtility.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#define FULL_DEBUG
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Cosmos.VS.Package
{
public static class LogUtility
{
private static readonly object mLockObj = new object();
[Conditional("FULL_DEBUG")]
public static void LogString(string message, params object[] args)
{
#if FULL_DEBUG
lock (mLockObj)
{
File.AppendAllText(GetLogFilePath(), DateTime.Now.ToString() + " - " + String.Format(message, args) + Environment.NewLine);
}
#endif
}
public static void LogException(Exception e, bool dontThrow = false)
{
#if FULL_DEBUG
if (null != e) {
do {
LogString("Error : {0}", e.Message);
LogString("Stack : {0}", e.StackTrace);
e = e.InnerException;
} while (null != e);
}
#endif
if (!dontThrow) { throw new Exception("Error occurred", e); }
}
private static string _logFilePath;
private static string GetLogFilePath()
{
if (null != _logFilePath)
{
CreateDirectoryForFilePath(_logFilePath);
return _logFilePath;
}
_logFilePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"Cosmos", "CosmosPkg.log");
CreateDirectoryForFilePath(_logFilePath);
return _logFilePath;
}
private static void CreateDirectoryForFilePath(string filePath)
{
DirectoryInfo scannedDirectory = new FileInfo(filePath).Directory;
if (scannedDirectory.Exists)
return;
Stack<DirectoryInfo> missingDirectories = new Stack<DirectoryInfo>();
do
{
missingDirectories.Push(scannedDirectory);
scannedDirectory = scannedDirectory.Parent;
}
while (!scannedDirectory.Exists);
do
{
try { Directory.CreateDirectory(missingDirectories.Pop().FullName); }
catch { break; }
}
while (0 < missingDirectories.Count);
}
}
}