Logging
Version 6.1.0
In this article
PDFsharp supports logging as documented in Microsoft.Extensions.Logging.
Logger factory
PDFsharp uses a single logger factory that can be initialized when the applications starts up. If no logger factory is provided, no logging takes place. You can set or change the logger factory at any time.
static void Main(…)
{
// Create and set a logger factory.
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddFilter("PDFsharp", LogLevel.Information)
.AddConsole();
});
// Set the logger factory.
LogHost.Factory = loggerFactory;
// Create your PDF document with PDFsharp.
…
}
If you do not provide a logger factory, PDFsharp uses the NullLoggerFactory that comes with Microsoft.Extensions.Logging. Therefore, you always get a valid logger object and never have to check it for null.
Caution
You must not dispose the factory before the application ends. If you use PDFsharp e.g. in an ASP.NET application you must not use a logger factory if its lifetime is coupled with a request. Instead use a factory created for the lifetime of the application host.
LogHost
LogHost is a static class that provides access to the logger factory and a global logger. PDFsharp can only use a global logger.
You can access the PDFsharp default logger from
LogHost.Logger
and use it in your PDF document creation code.
LogHost.Logger.LogInformation("Hello, World!");
You also can create a private logger for your code using one of the following functions.
var logger1 = LogHost.CreateLogger("MyCategory");
var logger2 = LogHost.CreateLogger<MyCategoryType>();
PDFsharp specific logger
PDFsharp internally uses a set of specific loggers for different categories.
There is for instance the PdfSharpLogHost.PdfReadingLogger
that logs issues in connection with parsing existing PDF files.
If you change the logger factory singleton during the runtime of your application, each specific logger is recreated using this factory the next time it is used.
However, the specific loggers, categories and event IDs are not yet fully integrated in the existing source code.