cs11dotnet7/vs4win/Chapter04/Instrumenting/Program.cs

66 lines
2.1 KiB
C#
Raw Normal View History

2022-02-19 20:56:52 +01:00
using System.Diagnostics;
using System.Reflection;
2022-02-19 20:56:52 +01:00
using Microsoft.Extensions.Configuration;
Console.WriteLine("Warning! Versions 7.0.3xx and 7.0.4xx have bugs that cause an exception:");
Console.WriteLine("Microsoft.Extensions.Configuration.Binder version: {0}",
typeof(ConfigurationBinder).Assembly.GetCustomAttribute
<AssemblyFileVersionAttribute>()?.Version);
Console.WriteLine();
2022-02-19 20:56:52 +01:00
string logPath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.DesktopDirectory), "log.txt");
Console.WriteLine($"Writing to: {logPath}");
TextWriterTraceListener logFile = new(File.CreateText(logPath));
Trace.Listeners.Add(logFile);
// Text writer is buffered, so this option calls
// Flush() on all listeners after writing.
2022-02-19 20:56:52 +01:00
Trace.AutoFlush = true;
Debug.WriteLine("Debug says, I am watching!");
Trace.WriteLine("Trace says, I am watching!");
Console.WriteLine("Reading from appsettings.json in {0}",
arg0: Directory.GetCurrentDirectory());
Console.WriteLine();
Console.WriteLine("--appsettings.json contents--");
Console.WriteLine(File.ReadAllText(Path.Combine(
Directory.GetCurrentDirectory(), "appsettings.json")));
2022-02-19 20:56:52 +01:00
ConfigurationBuilder builder = new();
builder.SetBasePath(Directory.GetCurrentDirectory());
// Add the appsettings.json file to the processed configuration.
// Make reading this file mandatory so an exception will be thrown
// if the file is not found.
2022-02-19 20:56:52 +01:00
builder.AddJsonFile("appsettings.json",
optional: false, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
TraceSwitch ts = new(
displayName: "PacktSwitch",
description: "This switch is set via a JSON config.");
configuration.GetSection("PacktSwitch").Bind(ts);
// Output the trace switch level from appsettings.json.
Console.WriteLine($"Trace switch level: {ts.Level}");
2022-02-19 20:56:52 +01:00
Trace.WriteLineIf(ts.TraceError, "Trace error");
Trace.WriteLineIf(ts.TraceWarning, "Trace warning");
Trace.WriteLineIf(ts.TraceInfo, "Trace information");
Trace.WriteLineIf(ts.TraceVerbose, "Trace verbose");
2022-09-17 16:45:46 +02:00
int unitsInStock = 12;
LogSourceDetails(unitsInStock > 10);
Console.WriteLine("Press enter to exit.");
2022-09-17 16:45:46 +02:00
Console.ReadLine();