-
Notifications
You must be signed in to change notification settings - Fork 56
/
Log.cs
126 lines (125 loc) · 3.8 KB
/
Log.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Storage;
namespace ARDrone2Client.Common
{
public class Log
{
private static readonly object _SyncRoot = new object();
private static readonly SemaphoreSlim _Semaphore = new SemaphoreSlim(1);
static Log()
{
_DefaultFileName = string.Format("{0:yyyy-MM-dd HH-mm-ss}.log", DateTime.Now);
}
public Log()
{
_FileName = DefaultFileName;
}
private static Log _Instance = null;
public static Log Instance
{
get
{
if (_Instance == null)
{
lock (_SyncRoot)
{
if (_Instance == null)
{
_Instance = new Log();
}
}
}
return _Instance;
}
}
private static bool _Enabled = false;
public static bool Enabled
{
get
{
return _Enabled;
}
set
{
_Enabled = value;
}
}
private static string _DefaultFileName = string.Empty;
public static string DefaultFileName
{
get
{
return _DefaultFileName;
}
set
{
_DefaultFileName = value;
}
}
private string _FileName = string.Empty;
public string FileName
{
get
{
return _FileName;
}
set
{
_FileName = value;
}
}
private static string FormatException(Exception exception)
{
var sb = new StringBuilder();
sb.AppendLine("Date/time=" + DateTime.Now.ToString());
sb.AppendLine(exception.Message);
sb.AppendLine("Source=" + exception.Source);
sb.AppendLine("StackTrace=" + exception.StackTrace);
return sb.ToString();
}
public async Task WriteAsync(Exception exception)
{
await WriteAsync(FormatException(exception));
}
public async Task WriteFormatAsync(string format, params object[] args)
{
await WriteAsync(string.Format(format, args));
}
public async Task WriteLineAsync(string message)
{
await WriteAsync(message + System.Environment.NewLine);
}
public async Task WriteAsync(string message)
{
if (!Enabled)
return;
#if WINDOWS_PHONE
#else
await _Semaphore.WaitAsync();
await Task.Run(async () =>
{
try
{
var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(FileName, CreationCollisionOption.OpenIfExists);
await FileIO.AppendTextAsync(file, message);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
_Semaphore.Release();
}
}
);
#endif
}
}
}