Terraria ModLoader  0.11.4
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(Program.SavePath, "Logs")
 

Properties

static string LogPath [get, private set]
 

Static Private Member Functions

static void AddChatMessage (string msg, Color color)
 
static bool CanOpen (string fileName)
 
static void ConfigureAppenders ()
 
static void EnablePortablePDBTraces ()
 
static void FirstChanceExceptionHandler (object sender, FirstChanceExceptionEventArgs args)
 
static string GetNewLogFile (string baseName)
 
static void LogFirstChanceExceptions ()
 

Static Private Attributes

static List< string > ignoreContents
 
static List< string > ignoreMessages
 
static HashSet< string > ignoreSources
 
static List< string > ignoreThrowingMethods
 
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.AddChatMessage ( string  msg,
Color  color 
)
staticprivate

Definition at line 212 of file Logging.cs.

212  {
213  if (Main.gameMenu)
214  return;
215 
216  float soundVolume = Main.soundVolume;
217  Main.soundVolume = 0f;
218  Main.NewText(msg, color);
219  Main.soundVolume = soundVolume;
220  }
static bool Terraria.ModLoader.Logging.CanOpen ( string  fileName)
staticprivate

Definition at line 118 of file Logging.cs.

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

Definition at line 62 of file Logging.cs.

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

Definition at line 276 of file Logging.cs.

References Terraria.ModLoader.FrameworkVersion.Framework, and Terraria.ModLoader.FrameworkVersion.Version.

276  {
277  if (FrameworkVersion.Framework == Framework.NetFramework && FrameworkVersion.Version >= new Version(4, 7, 2))
278  Type.GetType("System.AppContextSwitches").GetField("_ignorePortablePDBsInStackTraces", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, -1);
279  }
static void Terraria.ModLoader.Logging.FirstChanceExceptionHandler ( object  sender,
FirstChanceExceptionEventArgs  args 
)
staticprivate

Definition at line 176 of file Logging.cs.

References Terraria.ModLoader.Console.

176  {
177  if (args.Exception == previousException ||
178  args.Exception is ThreadAbortException ||
179  ignoreSources.Contains(args.Exception.Source) ||
180  ignoreMessages.Any(str => args.Exception.Message?.Contains(str) ?? false) ||
181  ignoreThrowingMethods.Any(str => args.Exception.StackTrace?.Contains(str) ?? false))
182  return;
183 
184  var stackTrace = new StackTrace(true);
185  PrettifyStackTraceSources(stackTrace.GetFrames());
186  var traceString = stackTrace.ToString();
187 
188  if (ignoreContents.Any(traceString.Contains))
189  return;
190 
191  traceString = traceString.Substring(traceString.IndexOf('\n'));
192  var exString = args.Exception.GetType() + ": " + args.Exception.Message + traceString;
193  lock (pastExceptions) {
194  if (!pastExceptions.Add(exString))
195  return;
196  }
197 
198  previousException = args.Exception;
199  var msg = args.Exception.Message + " " + Language.GetTextValue("tModLoader.RuntimeErrorSeeLogsForFullTrace", Path.GetFileName(LogPath));
200 #if CLIENT
201  if (ModCompile.activelyModding)
202  AddChatMessage(msg, Color.OrangeRed);
203 #else
204  Console.ForegroundColor = ConsoleColor.DarkMagenta;
205  Console.WriteLine(msg);
206  Console.ResetColor();
207 #endif
208  tML.Warn(Language.GetTextValue("tModLoader.RuntimeErrorSilentlyCaughtException") + '\n' + exString);
209  }
static string LogPath
Definition: Logging.cs:25
static List< string > ignoreContents
Definition: Logging.cs:143
static void PrettifyStackTraceSources(StackFrame[] frames)
Definition: Logging.cs:250
static List< string > ignoreThrowingMethods
Definition: Logging.cs:165
static List< string > ignoreMessages
Definition: Logging.cs:155
Command can be used in server console during MP.
static HashSet< string > ignoreSources
Definition: Logging.cs:138
static HashSet< string > pastExceptions
Definition: Logging.cs:135
static Exception previousException
Definition: Logging.cs:175
static void AddChatMessage(string msg, Color color)
Definition: Logging.cs:212
static string Terraria.ModLoader.Logging.GetNewLogFile ( string  baseName)
staticprivate

Definition at line 94 of file Logging.cs.

References Terraria.ModLoader.Console.

94  {
95  var pattern = new Regex($"{baseName}(\\d*)\\.log");
96  var existingLogs = Directory.GetFiles(LogDir).Where(s => pattern.IsMatch(Path.GetFileName(s))).ToList();
97 
98  if (!existingLogs.All(CanOpen)) {
99  int n = existingLogs.Select(s => {
100  var tok = pattern.Match(Path.GetFileName(s)).Groups[1].Value;
101  return tok.Length == 0 ? 1 : int.Parse(tok);
102  }).Max();
103  return $"{baseName}{n + 1}.log";
104  }
105 
106  foreach (var existingLog in existingLogs.OrderBy(File.GetCreationTime))
107  try {
108  File.Move(existingLog, existingLog + ".old");
109  }
110  catch (IOException) {
111  // Archiving has failed. Old log will be truncated. Display message to server console since logging won't work. Useful for tail command utilization
112  Console.WriteLine($"The log file, {existingLog}, is in use and can't be archived. Old log data will be forgotten.");
113  }
114 
115  return $"{baseName}.log";
116  }
Command can be used in server console during MP.
static readonly string LogDir
Definition: Logging.cs:24
static bool CanOpen(string fileName)
Definition: Logging.cs:118
static void Terraria.ModLoader.Logging.IgnoreExceptionContents ( string  source)
static

Definition at line 170 of file Logging.cs.

170  {
171  if (!ignoreContents.Contains(source))
172  ignoreContents.Add(source);
173  }
static List< string > ignoreContents
Definition: Logging.cs:143
static void Terraria.ModLoader.Logging.IgnoreExceptionSource ( string  source)
static
static void Terraria.ModLoader.Logging.LogFirstChanceExceptions ( )
staticprivate

Definition at line 128 of file Logging.cs.

References Terraria.ModLoader.FrameworkVersion.Framework.

128  {
129  if (FrameworkVersion.Framework == Framework.Mono)
130  tML.Warn("First-chance exception reporting is not implemented on Mono");
131 
132  AppDomain.CurrentDomain.FirstChanceException += FirstChanceExceptionHandler;
133  }
static void FirstChanceExceptionHandler(object sender, FirstChanceExceptionEventArgs args)
Definition: Logging.cs:176
static void Terraria.ModLoader.Logging.PrettifyStackTraceSources ( StackFrame[]  frames)
static

Definition at line 250 of file Logging.cs.

250  {
251  if (frames == null)
252  return;
253 
254  foreach (var frame in frames) {
255  string filename = frame.GetFileName();
256  var assembly = frame.GetMethod()?.DeclaringType?.Assembly;
257  if (filename == null || assembly == null)
258  continue;
259 
260  string trim;
261  if (AssemblyManager.GetAssemblyOwner(assembly, out var modName))
262  trim = modName;
263  else if (assembly == TerrariaAssembly)
264  trim = "tModLoader";
265  else
266  continue;
267 
268  int idx = filename.LastIndexOf(trim, StringComparison.InvariantCultureIgnoreCase);
269  if (idx > 0) {
270  filename = filename.Substring(idx);
271  f_fileName.SetValue(frame, filename);
272  }
273  }
274  }
static readonly Assembly TerrariaAssembly
Definition: Logging.cs:248

Member Data Documentation

List<string> Terraria.ModLoader.Logging.ignoreContents
staticprivate
Initial value:
= new List<string> {
"System.Console.set_OutputEncoding",
"Terraria.ModLoader.ModCompile",
"Delegate.CreateDelegateNoSecurityCheck",
"MethodBase.GetMethodBody",
"Terraria.Net.Sockets.TcpSocket.Terraria.Net.Sockets.ISocket.AsyncSend",
"System.Diagnostics.Process.Kill",
"Terraria.ModLoader.Core.AssemblyManager.CecilAssemblyResolver.Resolve",
}

Definition at line 143 of file Logging.cs.

List<string> Terraria.ModLoader.Logging.ignoreMessages
staticprivate
Initial value:
= new List<string> {
"A blocking operation was interrupted by a call to WSACancelBlockingCall",
"The request was aborted: The request was canceled.",
"Object name: 'System.Net.Sockets.Socket'.",
"Object name: 'System.Net.Sockets.NetworkStream'",
"This operation cannot be performed on a completed asynchronous result object.",
"Object name: 'SslStream'.",
"Unable to load DLL 'Microsoft.DiaSymReader.Native.x86.dll'"
}

Definition at line 155 of file Logging.cs.

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

Definition at line 138 of file Logging.cs.

List<string> Terraria.ModLoader.Logging.ignoreThrowingMethods
staticprivate
Initial value:
= new List<string> {
"at Terraria.Lighting.doColors_Mode",
"System.Threading.CancellationToken.Throw",
}

Definition at line 165 of file Logging.cs.

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

Definition at line 24 of file Logging.cs.

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

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

Definition at line 135 of file Logging.cs.

Exception Terraria.ModLoader.Logging.previousException
staticprivate

Definition at line 175 of file Logging.cs.

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

Definition at line 222 of file Logging.cs.

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

Definition at line 248 of file Logging.cs.

Property Documentation

string Terraria.ModLoader.Logging.LogPath
staticgetprivate set

Definition at line 25 of file Logging.cs.