Terraria ModLoader  0.10.1.5
A framework for Terraria mods
Terraria.ModLoader.Logging Class Reference
+ Collaboration diagram for Terraria.ModLoader.Logging:

Static Public Member Functions

static void IgnoreExceptionContents (string source)
 
static void IgnoreExceptionSource (string source)
 
static void PrettifyStackTraceSources (StackFrame[] frames)
 

Static Public Attributes

static readonly string LogDir = Path.Combine(Main.SavePath, "Logs")
 

Properties

static string LogPath [get, private set]
 

Private Member Functions

delegate void ctor_StackTrace (StackTrace self, Exception e, bool fNeedFileInfo)
 
delegate Encoding hook_GetEncoding (orig_GetEncoding orig, string name)
 
delegate void hook_StackTrace (ctor_StackTrace orig, StackTrace self, Exception e, bool fNeedFileInfo)
 
delegate Encoding orig_GetEncoding (string name)
 

Static Private Member Functions

static void Archive (string logPath)
 
static bool CanOpen (string fileName)
 
static void ConfigureAppenders ()
 
static void DeleteOldArchives ()
 
static void FirstChanceExceptionHandler (object sender, FirstChanceExceptionEventArgs args)
 
static Encoding HookGetEncoding (orig_GetEncoding orig, string name)
 
static void HookModuleLoad ()
 
static void HookStackTraceEx (ctor_StackTrace orig, StackTrace self, Exception e, bool fNeedFileInfo)
 
static void PrettifyStackTraceSources ()
 
static string RollLogs (string baseName)
 

Private Attributes

const int MAX_LOGS = 20
 

Static Private Attributes

static readonly FieldInfo f_strFileName
 
static List< string > ignoreContents
 
static HashSet< string > ignoreSources
 
static HashSet< string > pastExceptions = new HashSet<string>()
 
static Exception previousException
 
static Regex statusRegex = new Regex(@"(.+?)[: \d]*%$")
 
static readonly Assembly TerrariaAssembly = Assembly.GetExecutingAssembly()
 

Detailed Description

Definition at line 22 of file Logging.cs.

Member Function Documentation

static void Terraria.ModLoader.Logging.Archive ( string  logPath)
staticprivate

Definition at line 127 of file Logging.cs.

127  {
128  var time = File.GetCreationTime(logPath);
129  int n = 1;
130 
131  var pattern = new Regex($"{time:yyyy-MM-dd}-(\\d+)\\.zip");
132  var existingLogs = Directory.GetFiles(LogDir).Where(s => pattern.IsMatch(Path.GetFileName(s))).ToList();
133  if (existingLogs.Count > 0)
134  n = existingLogs.Select(s => int.Parse(pattern.Match(Path.GetFileName(s)).Groups[1].Value)).Max() + 1;
135 
136  using (var zip = new ZipFile(Path.Combine(LogDir, $"{time:yyyy-MM-dd}-{n}.zip"), Encoding.UTF8)) {
137  zip.AddFile(logPath, "");
138  zip.Save();
139  }
140 
141  File.Delete(logPath);
142  }
static readonly string LogDir
Definition: Logging.cs:24
static bool Terraria.ModLoader.Logging.CanOpen ( string  fileName)
staticprivate

Definition at line 117 of file Logging.cs.

117  {
118  try {
119  using (new FileStream(fileName, FileMode.Append)) ;
120  return true;
121  }
122  catch (IOException) {
123  return false;
124  }
125  }
static void Terraria.ModLoader.Logging.ConfigureAppenders ( )
staticprivate

Definition at line 65 of file Logging.cs.

65  {
66  var layout = new PatternLayout {
67  ConversionPattern = "[%d{HH:mm:ss}] [%t/%level] [%logger]: %m%n"
68  };
69  layout.ActivateOptions();
70 
71  var appenders = new List<IAppender>();
72 #if CLIENT
73  appenders.Add(new ConsoleAppender {
74  Name = "ConsoleAppender",
75  Layout = layout
76  });
77 #else
78  appenders.Add(new DebugAppender {
79  Name = "DebugAppender",
80  Layout = layout
81  });
82 #endif
83 
84  var fileAppender = new FileAppender {
85  Name = "FileAppender",
86  File = LogPath = Path.Combine(LogDir, RollLogs(side)),
87  AppendToFile = false,
88  Encoding = Encoding.UTF8,
89  Layout = layout
90  };
91  fileAppender.ActivateOptions();
92  appenders.Add(fileAppender);
93 
94  BasicConfigurator.Configure(appenders.ToArray());
95  }
static string LogPath
Definition: Logging.cs:25
static string RollLogs(string baseName)
Definition: Logging.cs:97
static readonly string LogDir
Definition: Logging.cs:24
delegate void Terraria.ModLoader.Logging.ctor_StackTrace ( StackTrace  self,
Exception  e,
bool  fNeedFileInfo 
)
private
static void Terraria.ModLoader.Logging.DeleteOldArchives ( )
staticprivate

Definition at line 145 of file Logging.cs.

145  {
146  var pattern = new Regex(".*\\.zip");
147  var existingLogs = Directory.GetFiles(LogDir).Where(s => pattern.IsMatch(Path.GetFileName(s))).OrderBy(File.GetCreationTime).ToList();
148  foreach (var f in existingLogs.Take(existingLogs.Count - MAX_LOGS)) {
149  try {
150  File.Delete(f);
151  }
152  catch (IOException) { }
153  }
154  }
static readonly string LogDir
Definition: Logging.cs:24
static void Terraria.ModLoader.Logging.FirstChanceExceptionHandler ( object  sender,
FirstChanceExceptionEventArgs  args 
)
staticprivate

Definition at line 195 of file Logging.cs.

References Terraria.ModLoader.Console.

195  {
196  if (args.Exception == previousException ||
197  args.Exception is ThreadAbortException ||
198  ignoreSources.Contains(args.Exception.Source))
199  return;
200 
201  var stackTrace = new StackTrace(true);
202  PrettifyStackTraceSources(stackTrace.GetFrames());
203  var traceString = stackTrace.ToString();
204 
205  if (ignoreSources.Any(traceString.Contains))
206  return;
207 
208  traceString = traceString.Substring(traceString.IndexOf('\n'));
209  var exString = args.Exception.GetType() + ": " + args.Exception.Message + traceString;
210  if (!pastExceptions.Add(exString))
211  return;
212 
213  previousException = args.Exception;
214  var msg = args.Exception.Message + " " + Language.GetTextValue("tModLoader.RuntimeErrorSeeLogsForFullTrace", Path.GetFileName(LogPath));
215 #if CLIENT
216  if (Main.ContentLoaded) {
217  float soundVolume = Main.soundVolume;
218  Main.soundVolume = 0f;
219  Main.NewText(msg, Microsoft.Xna.Framework.Color.OrangeRed);
220  Main.soundVolume = soundVolume;
221  }
222 #else
223  Console.ForegroundColor = ConsoleColor.DarkMagenta;
224  Console.WriteLine(msg);
225  Console.ResetColor();
226 #endif
227  tML.Warn(Language.GetTextValue("tModLoader.RuntimeErrorSilentlyCaughtException") + '\n' + exString);
228  }
static string LogPath
Definition: Logging.cs:25
Command can be used in server console during MP.
static HashSet< string > ignoreSources
Definition: Logging.cs:178
static HashSet< string > pastExceptions
Definition: Logging.cs:175
static Exception previousException
Definition: Logging.cs:194
static void PrettifyStackTraceSources()
Definition: Logging.cs:300
delegate Encoding Terraria.ModLoader.Logging.hook_GetEncoding ( orig_GetEncoding  orig,
string  name 
)
private
delegate void Terraria.ModLoader.Logging.hook_StackTrace ( ctor_StackTrace  orig,
StackTrace  self,
Exception  e,
bool  fNeedFileInfo 
)
private
static Encoding Terraria.ModLoader.Logging.HookGetEncoding ( orig_GetEncoding  orig,
string  name 
)
staticprivate

Definition at line 254 of file Logging.cs.

254  {
255  if (name == "IBM437")
256  return null;
257 
258  return orig(name);
259  }
static void Terraria.ModLoader.Logging.HookModuleLoad ( )
staticprivate

Definition at line 156 of file Logging.cs.

156  {
157  AssemblyManager.AssemblyResolveEarly((sender, args) => {
158  tML.DebugFormat("Assembly Resolve: {0} -> {1}", args.RequestingAssembly, args.Name);
159  return null;
160  });
161  }
static void Terraria.ModLoader.Logging.HookStackTraceEx ( ctor_StackTrace  orig,
StackTrace  self,
Exception  e,
bool  fNeedFileInfo 
)
staticprivate

Definition at line 268 of file Logging.cs.

268  {
269  orig(self, e, fNeedFileInfo);
270  if (fNeedFileInfo)
271  PrettifyStackTraceSources(self.GetFrames());
272  }
static void PrettifyStackTraceSources()
Definition: Logging.cs:300
static void Terraria.ModLoader.Logging.IgnoreExceptionContents ( string  source)
static

Definition at line 189 of file Logging.cs.

189  {
190  if (!ignoreContents.Contains(source))
191  ignoreContents.Add(source);
192  }
static List< string > ignoreContents
Definition: Logging.cs:183
static void Terraria.ModLoader.Logging.IgnoreExceptionSource ( string  source)
static
delegate Encoding Terraria.ModLoader.Logging.orig_GetEncoding ( string  name)
private
static void Terraria.ModLoader.Logging.PrettifyStackTraceSources ( StackFrame[]  frames)
static

Definition at line 274 of file Logging.cs.

274  {
275  if (frames == null)
276  return;
277 
278  foreach (var frame in frames) {
279  string filename = frame.GetFileName();
280  var assembly = frame.GetMethod()?.DeclaringType?.Assembly;
281  if (filename == null || assembly == null)
282  continue;
283 
284  string trim;
285  if (AssemblyManager.GetAssemblyOwner(assembly, out var modName))
286  trim = modName;
287  else if (assembly == TerrariaAssembly)
288  trim = "tModLoader";
289  else
290  continue;
291 
292  int idx = filename.LastIndexOf(trim, StringComparison.InvariantCultureIgnoreCase);
293  if (idx > 0) {
294  filename = filename.Substring(idx);
295  f_strFileName.SetValue(frame, filename);
296  }
297  }
298  }
static readonly Assembly TerrariaAssembly
Definition: Logging.cs:264
static readonly FieldInfo f_strFileName
Definition: Logging.cs:261
static void Terraria.ModLoader.Logging.PrettifyStackTraceSources ( )
staticprivate

Definition at line 300 of file Logging.cs.

300  {
301  if (f_strFileName == null)
302  return;
303 
304  new Hook(typeof(StackTrace).GetConstructor(new[] { typeof(Exception), typeof(bool) }), new hook_StackTrace(HookStackTraceEx));
305  }
delegate void hook_StackTrace(ctor_StackTrace orig, StackTrace self, Exception e, bool fNeedFileInfo)
static void HookStackTraceEx(ctor_StackTrace orig, StackTrace self, Exception e, bool fNeedFileInfo)
Definition: Logging.cs:268
static readonly FieldInfo f_strFileName
Definition: Logging.cs:261
static string Terraria.ModLoader.Logging.RollLogs ( string  baseName)
staticprivate

Definition at line 97 of file Logging.cs.

97  {
98  var pattern = new Regex($"{baseName}(\\d*)\\.log");
99  var existingLogs = Directory.GetFiles(LogDir).Where(s => pattern.IsMatch(Path.GetFileName(s))).ToList();
100 
101  if (!existingLogs.All(CanOpen)) {
102  int n = existingLogs.Select(s => {
103  var tok = pattern.Match(Path.GetFileName(s)).Groups[1].Value;
104  return tok.Length == 0 ? 1 : int.Parse(tok);
105  }).Max();
106  return $"{baseName}{n + 1}.log";
107  }
108 
109  foreach (var existingLog in existingLogs.OrderBy(File.GetCreationTime))
110  Archive(existingLog);
111 
113 
114  return $"{baseName}.log";
115  }
static void DeleteOldArchives()
Definition: Logging.cs:145
static readonly string LogDir
Definition: Logging.cs:24
static bool CanOpen(string fileName)
Definition: Logging.cs:117
static void Archive(string logPath)
Definition: Logging.cs:127

Member Data Documentation

readonly FieldInfo Terraria.ModLoader.Logging.f_strFileName
staticprivate
Initial value:
=
typeof(StackFrame).GetField("strFileName", BindingFlags.Instance | BindingFlags.NonPublic)

Definition at line 261 of file Logging.cs.

List<string> Terraria.ModLoader.Logging.ignoreContents
staticprivate
Initial value:
= new List<string> {
"Terraria.ModLoader.ModCompile",
"Delegate.CreateDelegateNoSecurityCheck",
"MethodBase.GetMethodBody",
}

Definition at line 183 of file Logging.cs.

HashSet<string> Terraria.ModLoader.Logging.ignoreSources
staticprivate
Initial value:
= new HashSet<string> {
"MP3Sharp"
}

Definition at line 178 of file Logging.cs.

readonly string Terraria.ModLoader.Logging.LogDir = Path.Combine(Main.SavePath, "Logs")
static

Definition at line 24 of file Logging.cs.

Referenced by Terraria.ModLoader.ErrorLogger.ClearLogs().

const int Terraria.ModLoader.Logging.MAX_LOGS = 20
private

Definition at line 144 of file Logging.cs.

HashSet<string> Terraria.ModLoader.Logging.pastExceptions = new HashSet<string>()
staticprivate

Definition at line 175 of file Logging.cs.

Exception Terraria.ModLoader.Logging.previousException
staticprivate

Definition at line 194 of file Logging.cs.

Regex Terraria.ModLoader.Logging.statusRegex = new Regex(@"(.+?)[: \d]*%$")
staticprivate

Definition at line 230 of file Logging.cs.

readonly Assembly Terraria.ModLoader.Logging.TerrariaAssembly = Assembly.GetExecutingAssembly()
staticprivate

Definition at line 264 of file Logging.cs.

Property Documentation

string Terraria.ModLoader.Logging.LogPath
staticgetprivate set

Definition at line 25 of file Logging.cs.