How to Do Logging in C# Without Using 3Rd Party Libraries

How do I do logging in C# without using 3rd party libraries?

public void Logger(string lines)
{
//Write the string to a file.append mode is enabled so that the log
//lines get appended to test.txt than wiping content and writing the log

using(System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt", true))
{
file.WriteLine(lines);
}
}

For more information MSDN

How to log to a file without using third party logger in .Net Core 3 ASP.NET MVC?

If ASP.NET Core 3 MVC doesn't have such built-in functionality the code of using third-party logging providers will be acceptable for me.

MS officially recommends to use 3rd party file loggers.

Using Serilog is also very convenient in asp.net core 3.0:

1.program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog((ctx, config) => { config.ReadFrom.Configuration(ctx.Configuration); })
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});

2.appsettings.json

"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],

"WriteTo": [
{ "Name": "Console" },
{ "Name": "Debug" },
{
"Name": "File",
"Args": {
"path": "log-{Date}.txt",
"rollingInterval": "Day",
"shared": true
}
}
],
"Properties": {
"Application": "SampleApp"
}
}

3.Use the following NuGet packages

<ItemGroup>    
<PackageReference Include="Serilog.AspNetCore" Version="3.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.1.1-dev-00209" />
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
</ItemGroup>

4. In controller:

public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}

public async Task Index()
{
_logger.LogInformation("Hello, World!");
}
}

Then you could check the txt file existing in your project.

Refer to https://github.com/serilog/serilog-sinks-file

Logging in a C# library

The beauty of using log4net is that your library doesn't have to specify where something is logged. The destination (log appenders) of the log messages is determined by the configuration, which is specified by the application (typically in a config file).

So yes, use log4net following their recommended patterns (a unique "logger" per class) and inform your users that your library uses log4net. Any log messages that your library code generates will be routed according to the consumers configuration (file, database, console, trace, etc).

EDIT: Here is a good short primer on log4net that explains the basic concepts.

How to log to a file using different third party logger in .Net Core? Third party logger may change dynamically when application starts

In this case, the logging is not an "external tool", it is a part of the application. That's why you can't implement a "generic" logging, you have to have it compiled into your app. But you are not limited to only one. You could compile in all three of them, and during the startup initialize the one you need based on the configuration

var factory = Configuration["LoggingSystem"] switch
{
"log4net" => loggerFactory.AddLog4Net(),
"nlog" => loggerFactory.AddNLog(),
...
_ => throw new Exception()
};

Of course that means your app should reference all the nugets, but that shouldn't be a problem.

c# Best Method to create a log file

I would not use third party libraries, I would log to an xml file.

This is a code sample that do logging to a xml file from different threads:

private static readonly object Locker = new object();
private static XmlDocument _doc = new XmlDocument();

static void Main(string[] args)
{
if (File.Exists("logs.txt"))
_doc.Load("logs.txt");
else
{
var root = _doc.CreateElement("hosts");
_doc.AppendChild(root);
}

for (int i = 0; i < 100; i++)
{
new Thread(new ThreadStart(DoSomeWork)).Start();
}
}

static void DoSomeWork()
{
/*
* Here you will build log messages
*/
Log("192.168.1.15", "alive");
}

static void Log(string hostname, string state)
{
lock (Locker)
{
var el = (XmlElement)_doc.DocumentElement.AppendChild(_doc.CreateElement("host"));
el.SetAttribute("Hostname", hostname);
el.AppendChild(_doc.CreateElement("State")).InnerText = state;
_doc.Save("logs.txt");
}
}

Best way to organize third party libraries with console applications

Have you looked at ilmerge? You should be able to ilmerge your log4net.dll into you executable to make it standalone.

Example usage (as a post-build step):

"$(SolutionDir)Lib\ilmerge" /targetplatform:v4,C:\Windows\Microsoft.NET\Framework\v4.0.30319 /out:$(ProjectDir)bin\Merged\MyExe.exe MyExe.exe log4net.net40.dll

Suppress 3rd party library console output?

Well you can use Console.SetOut to an implementation of TextWriter which doesn't write anywhere:

Console.SetOut(TextWriter.Null);

That will suppress all console output though. You could always maintain a reference to the original Console.Out writer and use that for your own output.

best approach for Logging/Error Handling framework for a C# .NET v3.5 application? (enterprise library / log4net / ?)

+1 for log4net.

Regarding (b), I tend to define my own custom exceptions (all derived from the same base class e.g. "BusinessException") that are raised by the BLL for errors that need to be communicated to the user (input violates business rule, user authorization failed, ...). If the BLL is deployed as a Web Service, such exceptions are wrapped in a SOAP fault with a client(SOAP 1.1)/sender(SOAP 1.2) fault code.

Then in the UI tier, any BusinessException or FaultException with FaultCode.IsSenderFault = true indicates that the error message should be displayed to the end user. Any other exceptions are logged, and a generic message ("something bad happened") is shown to the end user.

Personally I think that distinguishing messages that are to be shown to the user can only sensibly be done in an application-specific way such as the above.

Regarding (c) you could write a custom log4net appender that sends serious errors to your web service (possibly asynchronously via MSMQ).

EDIT

In response to the comment, I don't know of any 3rd party framework that does this; we do it with a very lightweight in-house framework (which also has other basic stuff like a thin provider-model API around log4net so that our in-house code is not explicitly dependent on log4net and we will be able to switch to a different logging framework if a better one emerges, or if our app is deployed to sites where administrators prefer a different one).



Related Topics



Leave a reply



Submit