public void Appendで3行ログを追加すると通常ログが3行になる() { const int logKind = 2; //固定ログの種類 const string fileName = "BlackJumboDog.Log"; //setUp var dir = TestUtil.GetTmpPath(TmpDir); Directory.CreateDirectory(dir); var sut = new LogFile(dir, logKind, logKind, 0, true); sut.Append( new OneLog("2012/06/01 00:00:00\tDetail\t3208\tWeb-localhost:88\t127.0.0.1\t0000018\texecute\tramapater")); sut.Append( new OneLog("2012/06/02 00:00:00\tError\t3208\tWeb-localhost:88\t127.0.0.1\t0000018\texecute\tramapater")); sut.Append( new OneLog("2012/06/03 00:00:00\tSecure\t3208\tWeb-localhost:88\t127.0.0.1\t0000018\texecute\tramapater")); sut.Dispose(); const int expected = 3; //exercise var lines = File.ReadAllLines(String.Format("{0}\\{1}", dir, fileName)); var actual = lines.Length; //verify Assert.That(actual, Is.EqualTo(expected)); }
private void WriteLog() { if (_logging) { try { if (LogFile.Length > Conf.LogFileSizeKB * 1024) { LogFile.Append( "<tr><td style=\"color:red\" valign=\"top\">Logging Exiting</td><td valign=\"top\">" + DateTime.Now.ToLongTimeString() + "</td><td valign=\"top\">Logging is being disabled as it has reached the maximum size (" + Conf.LogFileSizeKB + "kb).</td></tr>"); _logging = false; } if (_lastlog.Length != LogFile.Length) { string fc = LogTemplate.Replace("<!--CONTENT-->", LogFile.ToString()).Replace("<!--VERSION-->", Application. ProductVersion); File.WriteAllText(Program.AppDataPath + @"log_" + NextLog + ".htm", fc); _lastlog = LogFile.ToString(); } } catch (Exception) { _logging = false; } } }
// private static string logDirectory = ""; /// <summary> /// 记录异常 /// </summary> /// <param name="addr">引起异常的地址,比如网址</param> /// <param name="except"></param> public static void RecordException(string addr,Exception except) { if (PluginConfig.PLUGIN_LOG_OPENED) { Exception exc = except; DateTime dt = DateTime.Now; string dtStr = String.Format("{0:yyyyMMdd}", dt); string logDir = AppDomain.CurrentDomain.BaseDirectory + PluginConfig.PLUGIN_TMP_DIRECTORY + "logs"; //创建日志目录 if (!Directory.Exists(logDir)) { Directory.CreateDirectory(logDir).Create(); } LogFile logFile = new LogFile(logDir + "/" + dtStr + ".log"); if (exc.InnerException != null) { exc = except.InnerException; } Hashtable hash = new Hashtable(); hash.Add("addr", addr ?? "application"); hash.Add("message", exc.Message); hash.Add("stack", exc.StackTrace); hash.Add("time", String.Format("{0:yyyy-MM-dd HH:mm:ss}", dt)); hash.Add("source", exc.Source); //附加记录 logFile.Append(PluginConfig.PLUGIN_LOG_EXCEPT_FORMAT.Template(hash)); } throw except; //继续抛出异常 }
// private static string logDirectory = ""; /// <summary> /// 记录异常 /// </summary> /// <param name="addr">引起异常的地址,比如网址</param> /// <param name="except"></param> public static void RecordException(string addr, Exception except) { if (PluginConfig.PLUGIN_LOG_OPENED) { Exception exc = except; DateTime dt = DateTime.Now; string dtStr = String.Format("{0:yyyyMMdd}", dt); string logDir = AppDomain.CurrentDomain.BaseDirectory + PluginConfig.PLUGIN_TMP_DIRECTORY + "logs"; //创建日志目录 if (!Directory.Exists(logDir)) { Directory.CreateDirectory(logDir).Create(); } LogFile logFile = new LogFile(logDir + "/" + dtStr + ".log"); if (exc.InnerException != null) { exc = except.InnerException; } Hashtable hash = new Hashtable(); hash.Add("addr", addr ?? "application"); hash.Add("message", exc.Message); hash.Add("stack", exc.StackTrace); hash.Add("time", String.Format("{0:yyyy-MM-dd HH:mm:ss}", dt)); hash.Add("source", exc.Source); //附加记录 logFile.Append(PluginConfig.PLUGIN_LOG_EXCEPT_FORMAT.Template(hash)); } throw except; //继续抛出异常 }
static PluginAppBase() { plugins = new Dictionary <IPlugin, PluginPackAttribute>(); var pluginFilePattern = "*.dll"; string appDirectory = AppDomain.CurrentDomain.BaseDirectory; pluginDirectory = String.Concat( appDirectory, PluginConfig.PLUGIN_DIRECTORY); if (Directory.Exists(pluginDirectory)) { var loadResult = true; var files = Directory.GetFiles(pluginDirectory, pluginFilePattern ?? "*.dll"); log = new LogFile(appDirectory + PluginConfig.PLUGIN_TMP_DIRECTORY + "plugin.log"); log.Truncate(); if (log != null) { log.Append(String.Format("\r\n\r\n{0:yyyy-MM-dd HH:mm:ss} [+]Plugin Loading" + "\r\n========================================\r\n" + "Directory:{1} \t Total DLL:{2}", DateTime.Now, pluginDirectory.Replace("\\", "/"), files.Length.ToString())); } foreach (string file in files) { if (!LoadPlugin(file)) { loadResult = false; } } if (log != null) { log.Append(String.Format("\r\nload complete!result:{0}", loadResult ? "Ok" : "Error")); } } else { Directory.CreateDirectory(pluginDirectory).Create(); } }
static PluginAppBase() { plugins = new Dictionary<IPlugin, PluginPackAttribute>(); var pluginFilePattern = "*.dll"; string appDirectory = AppDomain.CurrentDomain.BaseDirectory; pluginDirectory = String.Concat( appDirectory, PluginConfig.PLUGIN_DIRECTORY); if (Directory.Exists(pluginDirectory)) { var loadResult = true; var files = Directory.GetFiles(pluginDirectory, pluginFilePattern ?? "*.dll"); log = new LogFile(appDirectory + PluginConfig.PLUGIN_TMP_DIRECTORY + "plugin.log"); log.Truncate(); if (log != null) { log.Append(String.Format("\r\n\r\n{0:yyyy-MM-dd HH:mm:ss} [+]Plugin Loading" + "\r\n========================================\r\n" + "Directory:{1} \t Total DLL:{2}", DateTime.Now, pluginDirectory.Replace("\\", "/"), files.Length.ToString())); } foreach (string file in files) { if (!LoadPlugin(file)) { loadResult = false; } } if (log != null) { log.Append(String.Format("\r\nload complete!result:{0}", loadResult ? "Ok" : "Error")); } } else { Directory.CreateDirectory(pluginDirectory).Create(); } }
public void ShouldCreateLogDirectoryIfNotExists() { GivenTestLogContains(/* empty */); _uut.Append(new TestIDEEvent()); _mockIoUtils.Verify(iou => iou.CreateDirectory(@"C:\My\Log\Dir")); }
internal static void LogWarningToFile(String message) { if (!_logging) { return; } try { LogFile.Append("<tr><td style=\"color:orange\" valign=\"top\">Warning</td><td valign=\"top\">" + DateTime.Now.ToLongTimeString() + "</td><td valign=\"top\">" + message + "</td></tr>"); } catch { //do nothing } }
internal static void LogExceptionToFile(Exception ex) { if (!_logging) { return; } try { string em = ex.HelpLink + "<br/>" + ex.Message + "<br/>" + ex.Source + "<br/>" + ex.StackTrace + "<br/>" + ex.InnerException + "<br/>" + ex.Data; LogFile.Append("<tr><td style=\"color:red\" valign=\"top\">Exception:</td><td valign=\"top\">" + DateTime.Now.ToLongTimeString() + "</td><td valign=\"top\">" + em + "</td></tr>"); } catch { } }
public void 過去7日分のログを準備して本日からsaveDaysでtailする() { //setUp var dir = TestUtil.GetTmpPath(TmpDir); Directory.CreateDirectory(dir); //2012/09/01~7日分のログを準備 var logFile = new LogFile(dir, 2, 2, 0, true); //最初は、保存期間指定なしで起動する logFile.Append( new OneLog("2012/09/01 00:00:00\tDetail\t3208\tWeb-localhost:88\t127.0.0.1\t0000018\texecute\tramapater")); logFile.Append( new OneLog("2012/09/02 00:00:00\tError\t3208\tWeb-localhost:88\t127.0.0.1\t0000018\texecute\tramapater")); logFile.Append( new OneLog("2012/09/03 00:00:00\tSecure\t3208\tWeb-localhost:88\t127.0.0.1\t0000018\texecute\tramapater")); logFile.Append( new OneLog("2012/09/04 00:00:00\tSecure\t3208\tWeb-localhost:88\t127.0.0.1\t0000018\texecute\tramapater")); logFile.Append( new OneLog("2012/09/05 00:00:00\tSecure\t3208\tWeb-localhost:88\t127.0.0.1\t0000018\texecute\tramapater")); logFile.Append( new OneLog("2012/09/06 00:00:00\tSecure\t3208\tWeb-localhost:88\t127.0.0.1\t0000018\texecute\tramapater")); logFile.Append( new OneLog("2012/09/07 00:00:00\tSecure\t3208\tWeb-localhost:88\t127.0.0.1\t0000018\texecute\tramapater")); logFile.Dispose(); const int expected = 2; //exercise //リフレクションを使用してprivateメソッドにアクセスする var cls = logFile; var type = cls.GetType(); var methodInfo = type.GetMethod("Tail", BindingFlags.NonPublic | BindingFlags.Instance); var dt = new DateTime(2012, 9, 7); //2012.9.7に設定する var path = string.Format("{0}\\BlackJumboDog.Log", dir); const int saveDays = 2; //保存期間2日 methodInfo.Invoke(cls, new object[] { path, saveDays, dt }); var actual = File.ReadAllLines(path).Length; //verify Assert.That(actual, Is.EqualTo(expected)); }
public static void Process(Exception e) { bool sendEmail = SprocketSettings.GetBooleanValue("SendErrorEmail"); HttpRequest Request = HttpContext.Current.Request; string strauth = ""; string form = ""; string headers = ""; string fulltext = ""; string path = ""; string divider = "----------------------------------------------------------" + Environment.NewLine; string cookies = ""; bool isAjax = false; try { isAjax = AjaxRequestHandler.IsAjaxRequest; } catch { } try { if (WebAuthentication.IsLoggedIn) { strauth = "Username: "******"[null]") + Environment.NewLine; } else { strauth = "The user was not signed in at the time." + Environment.NewLine; } strauth += "Host address/IP: " + Request.UserHostAddress + " / " + Request.UserHostName + Environment.NewLine; } catch (Exception ex) { strauth = "ERROR EVALUATING AUTHENTICATION STATE: " + ex + "\r\n\r\n"; } try { foreach (string key in HttpContext.Current.Request.Headers) { if (key == "Cookie") { cookies = "Cookie Data:" + Environment.NewLine; foreach (string k in Request.Headers[key].Split(';')) { string[] arr = k.Split('='); string val = arr.Length > 0 ? k.Substring(arr[0].Length + 1) : ""; cookies += "[ " + arr[0] + " ]" + Environment.NewLine + val + Environment.NewLine; } } else { headers += key + ": " + HttpContext.Current.Request.Headers[key] + Environment.NewLine; } } } catch (Exception ex) { headers = "ERROR EVALUATING HEADERS: " + ex + "\r\n\r\n"; } try { if (Request.Form.Count > 0) { form += Environment.NewLine + "FORM POST DATA:" + Environment.NewLine; foreach (string key in Request.Form.AllKeys) { form += key + ": " + Request.Form[key] + Environment.NewLine; } } else { form = "There was no form POST data (i.e. this was not a submitted form)." + Environment.NewLine; } } catch (Exception ex) { headers = "ERROR EVALUATING FORM POST DATA: " + ex + "\r\n\r\n"; } try { path = "The SprocketPath for the request was: " + SprocketPath.Value + Environment.NewLine; path += "The full URL was: " + Request.RawUrl + Environment.NewLine; } catch (Exception ex) { path = "ERROR EVALUATING SPROCKET PATH: " + ex + "\r\n\r\n"; } fulltext = "An exception was thrown by the application." + Environment.NewLine + strauth + divider + path + divider + form + divider + cookies + divider + "The HTTP Headers were:" + Environment.NewLine + headers + divider + "Program flow log:" + Environment.NewLine + ProgramFlowLog.Value + divider + "The exception thrown was:" + Environment.NewLine + e.ToString(); if (e.InnerException != null) { fulltext += Environment.NewLine + divider + "INNER EXCEPTION:" + Environment.NewLine + e.InnerException; } if (sendEmail) { try { EmailHandler.Send(EmailHandler.AdminEmailAddress, EmailHandler.NullEmailAddress, "APPLICATION ERROR", fulltext, false); } catch (Exception ex) { fulltext += "ERROR SENDING EMAIL: " + ex.ToString(); } } try { LogFile.Append(string.Format("error-{0:yyyy-MM-dd-HH-mm-ss-fff}.txt", DateTime.UtcNow), fulltext); } catch { } }
/// <summary> /// 加载单个插件 /// </summary> /// <param name="pluginFile"></param> public static bool LoadPlugin(string pluginFile) { PluginPackAttribute attribute = null; IPlugin obj = null; try { byte[] bytes = File.ReadAllBytes(pluginFile); var ass = Assembly.Load(bytes); var attbs = ass.GetCustomAttributes(typeof(PluginPackAttribute), true); if (attbs.Length != 0) { attribute = (PluginPackAttribute)attbs[0]; } else { //StringBuilder sb = new StringBuilder(); //foreach (object a in ass.GetCustomAttributes(true)) //{ // sb.Append("\r\n") // .Append(a.GetType() == typeof(PluginPackAttribute)); //} throw new NotSupportedException("不可识别的插件!请为程序集标记PluginPack特性!"); } var types = ass.GetTypes(); foreach (Type type in types) { if (type.IsClass) { foreach (Type t in type.GetInterfaces()) { if (t == typeof(IPlugin)) { obj = Activator.CreateInstance(type) as IPlugin; if (obj == null) { continue; } if (attribute != null) { plugins.Add(obj, attribute); } } } } } if (log != null) { log.Append(String.Format("\r\n{0}({1}) found plugin. version:{2}", attribute.Name, ass.GetName().Name, attribute.Version)); } } catch (Exception err) { if (log != null) { log.Append(String.Format("\r\nAssembly {0} happend exception:{1}", pluginFile.Substring(pluginFile.LastIndexOfAny(new char[] { '/', '\\' }) + 1), err.Message)); } return(false); } return(true); }