static void Main(string[] args) { var directory = args.Length == 0 ? "." : args[0]; directory = directory.EndsWith("\\") ? directory : directory + "\\"; TextWriterTraceListener log = null; try { using (var filestream = new FileStream(directory + "log.csv", FileMode.Create, FileAccess.Write, FileShare.Read)) { log = new TextWriterTraceListener(filestream); foreach (var file in new DirectoryInfo(directory).GetFiles().Select(file => file.Name)) { var begin = DateTime.Now; using (var source = new Bitmap(Image.FromFile(file))) { using (var bm = ConvertToGrayscale(source)) { bm.Save(string.Format("{0}{1}.{2}", directory, "gray", file)); } } var end = DateTime.Now; log.WriteLine(string.Format("{0},gray.{0},{1}", file, end - begin)); log.Flush(); } } } catch (Exception ex) { log.WriteLine(ex.Message); log.WriteLine(ex.StackTrace); } }
public void Test03() { string msg1, name; name = "MyXMLTraceWriter"; string fileName = string.Format("{0}_3.xml", this.GetType().Name); //Testing ctor(Stream, string) //Scenario 3: Vanilla - Pass in a valid name and check with the Name property try { CommonUtilities.DeleteFile(fileName); _stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write); _textWriter = new TextWriterTraceListener(_stream, name); Assert.True(_textWriter.Name == name); msg1 = "HelloWorld"; _textWriter.WriteLine(msg1); _textWriter.Dispose(); Assert.True(CommonUtilities.TestListenerContent(new Type[] { typeof(TextWriterTraceListener) }, new string[] { fileName }, msg1)); } finally { CommonUtilities.DeleteFile(fileName); } }
public void Delete() { var folder = sysIO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NUnit.System"); if (!sysIO.Directory.Exists(folder)) sysIO.Directory.CreateDirectory(folder); var testFile = sysIO.Path.Combine(folder, "test.txt"); sysIO.File.WriteAllText(testFile, "000" + Environment.NewLine); cIO.File.Delete(testFile); using (var log = new TextWriterTraceListener(testFile)) { log.WriteLine("11111"); } var content = sysIO.File.ReadAllText(testFile); Assert.False(content.Contains("0")); sysIO.File.Delete(testFile); }
public override void WriteLine(string message) { if (!enabled) { return; } tw.WriteLine(message); }
public static void LogExceptionToFile(Exception ex) { var logPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]); var logDirectory = logPath + @"\EXCEPTION"; var filePath = ""; if (!Directory.Exists(logDirectory)) { Directory.CreateDirectory(logDirectory); filePath = logDirectory + @"\EXCEPTION.0.log"; } else { var filePaths = Directory.GetFiles(logDirectory, "*.log"); if (filePaths.Length == 0) { filePath = logDirectory + @"\EXCEPTION.0.log"; } else { var fPath = filePaths[filePaths.Length - 1]; if (File.Exists(fPath)) { var lastestFile = new FileInfo(fPath); // > 2 MB if (((lastestFile.Length / 1024f) / 1024f) > 2) { var file = new FileInfo(fPath); var fileName = file.Name.Split('.'); filePath = logDirectory + @"\EXCEPTION." + (int.Parse(fileName[1]) + 1) + @".log"; } else { filePath = fPath; } } } } var a = Environment.NewLine; var logMessage = string.Concat(new object[] { ex.Message, Environment.NewLine, ex.Source, Environment.NewLine, ex.StackTrace, Environment.NewLine, ex.TargetSite, Environment.NewLine, ex.InnerException }); logMessage = DateTime.Now.ToString("HH:mm:ss") + " " + logMessage; var listener = new TextWriterTraceListener(filePath); listener.WriteLine(logMessage); listener.Flush(); listener.Close(); }
static void Main(string[] args) { RallyRestApi restApi = new RallyRestApi("*****@*****.**", "secret", "https://sandbox.rallydev.com", "v2.0"); DynamicJsonObject user = restApi.GetCurrentUser(); String userRef = user["_ref"]; String workspaceRef = "/workspace/12352608129"; //use valid workspace OID in your Rally String projectRef = "/project/14018981229"; //use valid project OID in your Rally System.Diagnostics.TextWriterTraceListener myListener = new System.Diagnostics.TextWriterTraceListener("log.log", "myListener"); try { //create story DynamicJsonObject myStory = new DynamicJsonObject(); myStory["Name"] = "my story " + DateTime.Now; myStory["Project"] = projectRef; myStory["Owner"] = userRef; CreateResult createStory = restApi.Create(workspaceRef, "HierarchicalRequirement", myStory); myStory = restApi.GetByReference(createStory.Reference, "FormattedID", "Owner", "Project"); myListener.WriteLine(DateTime.Now + "___________\r\n" + myStory["FormattedID"] + " Owner: " + myStory["Owner"]._refObjectName + " Project: " + myStory["Project"]._refObjectName); //update story myStory["Description"] = "updated " + DateTime.Now; //create tasks for (int i = 1; i <= 3; i++) { DynamicJsonObject myTask = new DynamicJsonObject(); myTask["Name"] = "task " + i + DateTime.Now; myTask["Owner"] = userRef; myTask["State"] = "In-Progress"; myTask["WorkProduct"] = myStory["_ref"]; CreateResult createTask = restApi.Create(workspaceRef, "Task", myTask); myTask = restApi.GetByReference(createTask.Reference, "FormattedID", "Owner", "State"); myListener.WriteLine(myTask["FormattedID"] + " State: " + myTask["StateX"]); } } catch(Exception e) { myListener.WriteLine(e); } myListener.Flush(); }
static void Main(string[] args) { RallyRestApi restApi = new RallyRestApi("*****@*****.**", "secret", "https://sandbox.rallydev.com", "v2.0"); DynamicJsonObject user = restApi.GetCurrentUser(); String userRef = user["_ref"]; String workspaceRef = "/workspace/12352608129"; //use valid workspace OID in your Rally String projectRef = "/project/14018981229"; //use valid project OID in your Rally System.Diagnostics.TextWriterTraceListener myListener = new System.Diagnostics.TextWriterTraceListener("log.log", "myListener"); try { //create story DynamicJsonObject myStory = new DynamicJsonObject(); myStory["Name"] = "my story " + DateTime.Now; myStory["Project"] = projectRef; myStory["Owner"] = userRef; CreateResult createStory = restApi.Create(workspaceRef, "HierarchicalRequirement", myStory); myStory = restApi.GetByReference(createStory.Reference, "FormattedID", "Owner", "Project"); myListener.WriteLine(DateTime.Now + "___________\r\n" + myStory["FormattedID"] + " Owner: " + myStory["Owner"]._refObjectName + " Project: " + myStory["Project"]._refObjectName); //update story myStory["Description"] = "updated " + DateTime.Now; //create tasks for (int i = 1; i <= 3; i++) { DynamicJsonObject myTask = new DynamicJsonObject(); myTask["Name"] = "task " + i + DateTime.Now; myTask["Owner"] = userRef; myTask["State"] = "In-Progress"; myTask["WorkProduct"] = myStory["_ref"]; CreateResult createTask = restApi.Create(workspaceRef, "Task", myTask); myTask = restApi.GetByReference(createTask.Reference, "FormattedID", "Owner", "State"); myListener.WriteLine(myTask["FormattedID"] + " State: " + myTask["StateX"]); } } catch (Exception e) { myListener.WriteLine(e); } myListener.Flush(); }
//寫入檔案 private static void WriteLineToFile(DateTime msgTime, CategoryFilterMode msglvl, int threadid, string threadName, string msg) { try { //換天時執行 if (DateTime.Today > _todayDateTime) { SetLogFile(m_FilePath, m_FileName, m_FileExp, m_ReserveDay); } string message; //DateTime msgtime = DateTime.Now; //if (threadName == null) //{ // string messageId = string.Format("<{0}.{1}>{2}", m_ProcessId, threadid, Enum.Format(typeof(CategoryFilterMode), msglvl, "G")); // message = string.Format("{0}-{1}-{2}-{3}", messageId, msglvl, msgtime.ToString(), msg); //} //else //{ // string messageId = string.Format("<{0}.{1}.{2}>{3}", m_ProcessId, threadid, threadName, Enum.Format(typeof(CategoryFilterMode), msglvl, "G")); // message = string.Format("{0}-{1}-{2}", messageId, msgtime.ToString(), msg); //} string msgtime = DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss.fff"); message = string.Format("{0} | {1} | {2} | {3} | {4}", msgtime, msglvl, GetMemoryLoad(), GetThreadPoolTaskNumber(), msg); //message = string.Format("{0} | {1} | {2} | {3}", msgtime, msglvl, GetThreadPoolTaskNumber(), msg); lock (objKey2) { if (myListener == null) { SetLogFilePath(string.Format(@"{0}\{1}", Application.StartupPath, "DefaultLog.log")); } myListener.WriteLine(message); myListener.Flush(); } } catch (Exception ex) { Log.Exception(ex); } }
/// <summary> /// Initializes a new log /// </summary> /// <param name="appName">Name of the application</param> public static string Initialize(string appName) { if (!Convert.ToBoolean(Settings.Default.Trace, CultureInfo.InvariantCulture)) return string.Empty; // This is going in a "ThoughtWorks" folder under the directory that serves as a // common repository for application-specific data that is used by the current, non-roaming user. var dir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\ThoughtWorks\\"; var di = new DirectoryInfo(dir); di.Create(); FilePath = string.Format("{0}{1}{2}{3}", dir, (string.IsNullOrEmpty(appName) ? string.Empty : appName), DateTime.Now.Ticks, ".log"); _fs = new FileStream(FilePath, FileMode.Append); Log = new TextWriterTraceListener(_fs); Trace.Listeners.Add(Log); Log.IndentSize = 4; Log.WriteLine(string.Format("{0}*** Log opened at {1} ***", FilePath, DateTime.Now.ToLongTimeString())); return FilePath; }
public void Test02() { try { //Testing ctor(Stream) //[] Vanilla - pass a valid stream. Also check via FileName return the expected value string msg1; _fileName = string.Format("{0}_2.xml", this.GetType().Name); CommonUtilities.DeleteFile(_fileName); _stream = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.Write); _textWriter = new TextWriterTraceListener(_stream); msg1 = "HelloWorld"; _textWriter.WriteLine(msg1); _textWriter.Dispose(); Assert.True(CommonUtilities.TestListenerContent(new Type[] { typeof(TextWriterTraceListener) }, new string[] { _fileName }, msg1)); } finally { CommonUtilities.DeleteFile(_fileName); } }
private void CreateLog(string activityLog, string errorLog, long logSize, int bufferSize, bool relativePath) { string logDirectory; try { if (errorLog == "") logError = false; if (relativePath) { //Path relativo -> Utilizo el path de la aplicación _LogActivity = AppPath() + "\\" + activityLog; _LogError = AppPath() + "\\" + errorLog; } else { //Path absoluto _LogActivity = activityLog; _LogError = errorLog; } logDirectory = Path.GetDirectoryName(_LogActivity); if (!Directory.Exists(logDirectory)) Directory.CreateDirectory(logDirectory); _LogSize = logSize; _BufferSize = bufferSize; string fecha = String.Format("{0:00}", DateTime.Now.Day) + "-" + String.Format("{0:00}", DateTime.Now.Month) + "-" + String.Format("{0:0000}", DateTime.Now.Year) + " a las " + String.Format("{0:00}", DateTime.Now.Hour) + ":" + String.Format("{0:00}", DateTime.Now.Minute) + ":" + String.Format("{0:00}", DateTime.Now.Second); string initLog = "**********************************************************\n" + "* Session del log iniciada (" + fecha + ") *\n" + "**********************************************************"; FileStreamWithBackup fileActivity = new FileStreamWithBackup(_LogActivity, _LogSize * 1024, FileMode.Append, FileShare.Read, bufferSize * 1024); fileActivity.CanSplitData = false; activityLogger = new TextWriterTraceListener(fileActivity); activityLogger.WriteLine(initLog); activityLogger.Flush(); if (logError) { FileStreamWithBackup fileError = new FileStreamWithBackup(_LogError, _LogSize * 1024, FileMode.Append, FileShare.Read, bufferSize * 1024); fileError.CanSplitData = false; errorLogger = new TextWriterTraceListener(fileError); errorLogger.WriteLine(initLog); errorLogger.Flush(); } } catch (Exception ex) { throw ex; } }
private static void EnableTraceLogging(OperationArguments operationArguments) { const int LogFileMaxLength = 8 * 1024 * 1024; // 8 MB Trace.WriteLine("Program::EnableTraceLogging"); if (operationArguments.WriteLog) { Trace.WriteLine(" trace logging enabled"); string gitConfigPath; if (Where.GitLocalConfig(out gitConfigPath)) { Trace.WriteLine(" git local config found at " + gitConfigPath); string dotGitPath = Path.GetDirectoryName(gitConfigPath); string logFilePath = Path.Combine(dotGitPath, Path.ChangeExtension(ConfigPrefix, ".log")); string logFileName = operationArguments.TargetUri.ToString(); FileInfo logFileInfo = new FileInfo(logFilePath); if (logFileInfo.Exists && logFileInfo.Length > LogFileMaxLength) { for (int i = 1; i < Int32.MaxValue; i++) { string moveName = String.Format("{0}{1:000}.log", ConfigPrefix, i); string movePath = Path.Combine(dotGitPath, moveName); if (!File.Exists(movePath)) { logFileInfo.MoveTo(movePath); break; } } } Trace.WriteLine(" trace log destination is " + logFilePath); var listener = new TextWriterTraceListener(logFilePath, logFileName); Trace.Listeners.Add(listener); // write a small header to help with identifying new log entries listener.WriteLine(Environment.NewLine); listener.WriteLine(String.Format("Log Start ({0:u})", DateTimeOffset.Now)); listener.WriteLine(String.Format("Microsoft {0} version {0}", Program.Title, Version.ToString(3))); } } }
/// <summary> /// 保存异常日志 /// </summary> /// <param name="exceptionMsg"></param> private void SaveExceptionInfo(string exceptionMsg) { if (!Directory.Exists(Path.GetDirectoryName(CommonInfo.ERRORLOGPATH))) { Directory.CreateDirectory(Path.GetDirectoryName(CommonInfo.ERRORLOGPATH)); } string fileName = CommonInfo.ERRORLOGPATH + DateTime.Now.ToString("yy-MM-dd") + ".log"; TextWriterTraceListener textWrite = new TextWriterTraceListener(fileName, "ExceptionLog"); textWrite.Flush(); textWrite.WriteLine(DateTime.Now.ToString() + "监控平台出现异常--------------------------------"); textWrite.WriteLine(exceptionMsg); textWrite.Flush(); textWrite.Close(); }
public void Test04() { string msg1, name; name = null; _fileName = string.Format("{0}_4.xml", this.GetType().Name); //Scenario 4: name is null -its set as the empty string try { CommonUtilities.DeleteFile(_fileName); _stream = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.Write); _textWriter = new TextWriterTraceListener(_stream, name); Assert.True(_textWriter.Name == string.Empty); msg1 = "HelloWorld"; _textWriter.WriteLine(msg1); _textWriter.Dispose(); Assert.True(CommonUtilities.TestListenerContent(new Type[] { typeof(TextWriterTraceListener) }, new string[] { _fileName }, msg1)); } finally { CommonUtilities.DeleteFile(_fileName); } }
public static void LogToFile(LogFileType logType, string logMessage) { //string LogPath = Environment.CurrentDirectory; var logPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);//@"C:\VNPT-BHXH"; var logDirectory = logPath + @"\" + DateTime.Today.ToString("yyyyMMdd"); string filePath; if (!Directory.Exists(logDirectory)) { Directory.CreateDirectory(logDirectory); switch (logType) { case LogFileType.Trace: filePath = logDirectory + @"\TRACE.0.log"; break; case LogFileType.Message: filePath = logDirectory + @"\MESSAGE.0.log"; break; case LogFileType.Exception: filePath = logDirectory + @"\EXCEPTION.0.log"; break; default: filePath = logDirectory + @"\TRACE.0.log"; break; } } else { var filePaths = Directory.GetFiles(logDirectory, "*.log"); if (filePaths.Length == 0) { switch (logType) { case LogFileType.Trace: filePath = logDirectory + @"\TRACE.0.log"; break; case LogFileType.Message: filePath = logDirectory + @"\MESSAGE.0.log"; break; case LogFileType.Exception: filePath = logDirectory + @"\EXCEPTION.0.log"; break; default: filePath = logDirectory + @"\TRACE.0.log"; break; } } else { var fileList = new List<string>(); foreach (var fPath in filePaths) { var file = new FileInfo(fPath); var parts = file.Name.Split('.'); if (parts[0].ToUpper() == logType.ToString().ToUpper()) { fileList.Add(fPath); } } var lastestIndex = int.MinValue; var lastestFilePath = ""; if (fileList.Count <= 0) { filePath = logDirectory + @"\" + logType.ToString().ToUpper() + ".0.log"; } else { foreach (var fPath in fileList) { var file = new FileInfo(fPath); var parts = file.Name.Split('.'); //fPath.Split('.'); if (Convert.ToInt32(parts[1]) >= lastestIndex) { lastestIndex = Convert.ToInt32(parts[1]); lastestFilePath = fPath; } } filePath = lastestFilePath; } if (File.Exists(filePath)) { var lastestFile = new FileInfo(filePath); // check if file size be larger than 5MB then create new one if (((lastestFile.Length / 1024f) / 1024f) > 5) { lastestIndex++; filePath = logDirectory + @"\" + logType.ToString().ToUpper() + "." + lastestIndex + ".log"; } } } } logMessage = DateTime.Now.ToString("HH:mm:ss") + " " + logMessage; var listener = new TextWriterTraceListener(filePath); listener.WriteLine(logMessage); listener.Flush(); listener.Close(); }
public void Test05() { string msg1; string[] names = { string.Empty, new string('a', 100000), "hell0<", "><&" }; string fileName = string.Format("{0}_5.xml", this.GetType().Name); //Scenario 6: Other interesting string values - empty, very long, interesting characters (ones that will clash with xml like <, >, etc) try { foreach (string name in names) { CommonUtilities.DeleteFile(fileName); _stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write); _textWriter = new TextWriterTraceListener(_stream, name); Assert.True(_textWriter.Name == name); msg1 = "HelloWorld"; _textWriter.WriteLine(msg1); _textWriter.Dispose(); Assert.True(CommonUtilities.TestListenerContent(new Type[] { typeof(TextWriterTraceListener) }, new string[] { fileName }, msg1)); } } finally { CommonUtilities.DeleteFile(fileName); } }
private static void InitLogger() { TraceSwitch = new TraceSwitch("RoamieTracing", "Roaming Tracing", "Warning"); try { TextWriterTraceListener writer = new TextWriterTraceListener(); writer.Writer = new StreamWriter(Application.StartupPath + @"\Roamie.log", true); writer.TraceOutputOptions = TraceOptions.Timestamp | TraceOptions.DateTime | TraceOptions.Callstack; writer.WriteLine("===== ROAMIE LOG BEGIN ====="); Trace.Listeners.Add(writer); Trace.AutoFlush = true; } catch { } }