本文整理汇总了C#中System.Diagnostics.TextWriterTraceListener.Flush方法的典型用法代码示例。如果您正苦于以下问题:C# TextWriterTraceListener.Flush方法的具体用法?C# TextWriterTraceListener.Flush怎么用?C# TextWriterTraceListener.Flush使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Diagnostics.TextWriterTraceListener
的用法示例。
在下文中一共展示了TextWriterTraceListener.Flush方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Enable debugging output to a logfile with the date and time of launch in the current directory
Assembly _assembly = typeof(MainForm).Assembly;
DateTime _now = DateTime.Now;
logPath = Path.GetDirectoryName(_assembly.Location) + "\\" +
_now.Year + "-" + _now.Month + "-" + _now.Day + "_" +
_now.Hour + "-" + _now.Minute + "-" + _now.Second + ".log";
Debug.WriteLine("[LogListener] Setting up Listener for log file " + logPath);
TextWriterTraceListener logListener = new TextWriterTraceListener(logPath);
Debug.Listeners.Add(logListener);
Debug.WriteLine("[LogListener] Log file " + logPath + " created");
// and start evetything
Debug.WriteLine("[Program] Starting new MainForm");
Application.Run(new MainForm());
Debug.WriteLine("[Program] Returned from MainForm, cleaning up");
logListener.Flush();
logListener.Dispose();
}
示例2: Main
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);
}
}
示例3: CorrelationIdTestAsync
public static async Task CorrelationIdTestAsync(Sts sts)
{
SetCredential(sts);
var context = new AuthenticationContextProxy(sts.Authority, sts.ValidateAuthority);
Guid correlationId = Guid.NewGuid();
AuthenticationResultProxy result = null;
MemoryStream stream = new MemoryStream();
using (var listener = new TextWriterTraceListener(stream))
{
Trace.Listeners.Add(listener);
context.SetCorrelationId(correlationId);
result = context.AcquireToken(sts.ValidResource, sts.ValidClientId, sts.ValidDefaultRedirectUri, PromptBehaviorProxy.Auto, sts.ValidUserId);
VerifySuccessResult(sts, result);
listener.Flush();
string trace = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Position);
Verify.IsTrue(trace.Contains(correlationId.ToString()));
Trace.Listeners.Remove(listener);
}
stream = new MemoryStream();
using (var listener = new TextWriterTraceListener(stream))
{
Trace.Listeners.Add(listener);
context.SetCorrelationId(Guid.Empty);
AuthenticationResultProxy result2 = await context.AcquireTokenByRefreshTokenAsync(result.RefreshToken, sts.ValidClientId);
Verify.IsNotNull(result2.AccessToken);
listener.Flush();
string trace = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Position);
Verify.IsFalse(trace.Contains(correlationId.ToString()));
Verify.IsTrue(trace.Contains("Correlation ID"));
Trace.Listeners.Remove(listener);
}
}
示例4: LogExceptionToFile
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();
}
示例5: Enable
public static IDisposable Enable(string path)
{
var listener = new TextWriterTraceListener(path);
_logging.Value.Sources.ForEach(s => s.Listeners.Add(listener));
return new DisposableAction(() =>
{
listener.Flush();
_logging.Value.Sources.ForEach(s => s.Listeners.Remove(listener));
listener.Close();
});
}
示例6: Main
static void Main(string[] args)
{
RallyRestApi restApi = new RallyRestApi("[email protected]", "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();
}
示例7: LaunchExample
static void LaunchExample(string type)
{
try
{
if (File.Exists("debug.log"))
File.Delete("debug.log");
if (File.Exists("trace.log"))
File.Delete("trace.log");
}
catch (Exception e)
{
Trace.WriteLine(String.Format("Could not access debug.log", e.ToString()));
}
using (TextWriterTraceListener dbg = new TextWriterTraceListener("debug.log"))
using (OpenTK.Toolkit.Init())
{
Trace.Listeners.Add(dbg);
try
{
var example = Type.GetType(type);
if (example != null)
{
example.InvokeMember("Main",
BindingFlags.InvokeMethod | BindingFlags.Static |
BindingFlags.Public | BindingFlags.NonPublic,
null, null, null);
}
}
catch (Exception e)
{
Trace.WriteLine(String.Format("Exception occured in example {0}: {1}",
type, e.ToString()));
}
Trace.Listeners.Remove(dbg);
dbg.Flush();
dbg.Close();
}
}
示例8: LaunchExample
static void LaunchExample(string type)
{
try
{
if (File.Exists("debug.log"))
File.Delete("debug.log");
if (File.Exists("trace.log"))
File.Delete("trace.log");
}
catch (Exception e)
{
Trace.WriteLine(String.Format("Could not access debug.log", e.ToString()));
}
ToolkitOptions options = ToolkitOptions.Default;
if (type.Contains("GLControl") || type.Contains("Form"))
{
// SDL does not currently support embedding in foreign windows
// such as GLControl. We need to use a native OpenTK.Platform
// backend in that case. This hack is specific to the example-browser
// architecture - you do not need to do anything like this in your
// own code (it will just work).
options = new ToolkitOptions
{
Backend = PlatformBackend.PreferNative
};
}
using (TextWriterTraceListener dbg = new TextWriterTraceListener("debug.log"))
using (Toolkit.Init(options))
{
Trace.Listeners.Add(dbg);
try
{
var example = Type.GetType(type);
if (example != null)
{
example.InvokeMember("Main",
BindingFlags.InvokeMethod | BindingFlags.Static |
BindingFlags.Public | BindingFlags.NonPublic,
null, null, null);
}
}
catch (Exception e)
{
Trace.WriteLine(String.Format("Exception occured in example {0}: {1}",
type, e.ToString()));
}
Trace.Listeners.Remove(dbg);
dbg.Flush();
dbg.Close();
}
}
示例9: PROCESS
//.........这里部分代码省略.........
DateTime.Now.ToLocalTime()), "Detect And Download From TheGamesDB.net");
int step_index = 0;
int steps_count = 4;
#region 1 Getting all platform entries from the internet
Trace.WriteLine("Getting entries for selected platform ...", "Detect And Download From TheGamesDB.net");
status_master = "Getting entries for selected platform ...";
progress_master = 100 / (steps_count - step_index);
// Get database content
Platform selectedPlatform = GamesDB.GetPlatform(_db_selected_platform_id);
List<GameSearchResult> databaseEntries = new List<GameSearchResult>(GamesDB.GetPlatformGames(_db_selected_platform_id));
Trace.WriteLine("Platform entries done, total of " + databaseEntries.Count + " entries found.", "Detect And Download From TheGamesDB.net");
#endregion
#region 2 Get the games
step_index++;
Trace.WriteLine("Collecting the roms ...", "Detect And Download From TheGamesDB.net");
status_master = "Collecting the roms ...";
progress_master = 100 / (steps_count - step_index);
DataSet set = MyNesDB.GetDataSet("GAMES");
Trace.WriteLine("Roms collected, total of " + set.Tables[0].Rows.Count + " entries", "Detect And Download From TheGamesDB.net");
// Clear detected files first ?
if (_clear_info_table)
MyNesDB.DeleteDetects("INFOS");
if (_clear_snaps_table)
MyNesDB.DeleteDetects("SNAPS");
if (_clear_covers_table)
MyNesDB.DeleteDetects("COVERS");
#endregion
#region 3 Compare and apply stuff
step_index++;
Trace.WriteLine("Comparing and applying naming", "Detect And Download From TheGamesDB.net");
status_master = "Comparing ...";
progress_master = 100 / (steps_count - step_index);
int gameEntriesCount = set.Tables[0].Rows.Count;
int matchedCount = 0;
List<string> matchedRomNames = new List<string>();
List<string> notMatchedRomNames = new List<string>();
for (int game_index = 0; game_index < gameEntriesCount; game_index++)
{
string id = set.Tables[0].Rows[game_index]["Id"].ToString();
string entryName = set.Tables[0].Rows[game_index]["Name"].ToString().Replace("'", "'");
string entryPath = set.Tables[0].Rows[game_index]["Path"].ToString().Replace("'", "'");
status_sub_sub = "";
// Loop through database entries looking for a match
for (int entry_index = 0; entry_index < databaseEntries.Count; entry_index++)
{
if (FilterSearch(entryName, entryPath, databaseEntries[entry_index].Title))
{
Trace.WriteLine("GAME MATCHED [" + id + "] (" + entryName + ")", "Detect And Download From TheGamesDB.net");
matchedRomNames.Add(entryName);
// Apply
ApplyRom(entryName, id, GamesDB.GetGame(databaseEntries[entry_index].ID));
Trace.WriteLine("ROM DATA UPDATED.", "Detect And Download From TheGamesDB.net");
matchedCount++;
if (_turbo_speed)
databaseEntries.RemoveAt(entry_index);
break;
}
}
// Progress
progress_sub = (game_index * 100) / gameEntriesCount;
status_sub = string.Format("{0} {1} / {2} ({3} MATCHED) ... {4} %",
Program.ResourceManager.GetString("Status_ApplyingDatabase"), (game_index + 1).ToString(), gameEntriesCount,
matchedCount.ToString(), progress_sub);
}
#endregion
#region 4 Update log with matched and not found roms
step_index++;
Trace.WriteLine("Finishing", "Detect And Download From TheGamesDB.net");
status_master = "Finishing ...";
progress_master = 100 / (steps_count - step_index);
Trace.WriteLine("----------------------------");
Trace.WriteLine("MATCHED ROMS ( total of " + matchedRomNames.Count + " rom(s) )");
Trace.WriteLine("------------");
for (int i = 0; i < matchedRomNames.Count; i++)
Trace.WriteLine((i + 1).ToString("D8") + "." + matchedRomNames[i]);
Trace.WriteLine("----------------------------");
Trace.WriteLine("ROMS NOT FOUND ( total of " + notMatchedRomNames.Count + " rom(s) )");
Trace.WriteLine("--------------");
for (int i = 0; i < notMatchedRomNames.Count; i++)
Trace.WriteLine((i + 1).ToString("D8") + "." + notMatchedRomNames[i]);
Trace.WriteLine("----------------------------");
Trace.WriteLine(string.Format("Detect And Download From TheGamesDB.net finished at {0}.", DateTime.Now.ToLocalTime()), "Detect And Download From TheGamesDB.net");
listner.Flush();
Trace.Listeners.Remove(listner);
CloseAfterFinish();
#endregion
}
示例10: CreateLog
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;
}
}
示例11: TestTraceLogger
public void TestTraceLogger()
{
var stream = new MemoryStream();
var listener = new TextWriterTraceListener(stream);
Trace.Listeners.Add(listener);
var logger = new TraceLogFactory().GetLogger("logger");
var logMsg = TestSupport.RandomString();
logger.Finest(logMsg);
logger.Info(logMsg);
logger.Warning(logMsg);
logger.Severe(logMsg);
listener.Flush();
stream.Seek(0, SeekOrigin.Begin);
var log = new StreamReader(stream).ReadToEnd();
Assert.That(log, Is.StringContaining("Information: 0 : " + logMsg));
Assert.That(log, Is.StringContaining("Warning: 0 : " + logMsg));
Assert.That(log, Is.StringContaining("Error: 0 : " + logMsg));
}
示例12: LogToFile
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();
}
示例13: Invoke
public void Invoke()
{
try
{
using (TextWriterTraceListener dbg = new TextWriterTraceListener("debug.log"))
{
Trace.Listeners.Add(dbg);
Trace.Listeners.Add(new ConsoleTraceListener());
_main.Invoke(null, null);
dbg.Flush();
dbg.Close();
}
}
catch (TargetInvocationException expt)
{
string ex_info;
if (expt.InnerException != null)
ex_info = expt.InnerException.ToString();
else
ex_info = expt.ToString();
//MessageBox.Show(ex_info, "An OpenTK example encountered an error.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
Trace.WriteLine(ex_info.ToString());
}
catch (Exception expt)
{
Trace.WriteLine(expt.ToString());
}
}
示例14: SaveExceptionInfo
/// <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();
}
示例15: when_tracing_activity_then_can_render_activity_as_string
public void when_tracing_activity_then_can_render_activity_as_string()
{
var writer = new StringWriter();
var text = new TextWriterTraceListener(writer);
manager.AddListener("*", text);
manager.SetTracingLevel("*", SourceLevels.All);
var tracer = Tracer.Get("Foo");
using (tracer.StartActivity("Outer"))
{
tracer.Info("Hello info from outer");
using (tracer.StartActivity("Inner"))
{
tracer.Warn("Warn from inner");
Tracer.Get("Foo.Bar").Error("Something failed on another class!");
}
}
System.Threading.Thread.Sleep(1000);
text.Flush();
Console.WriteLine(writer.ToString());
}