Posts tagged ‘Logging’
Quick, I need to add logging/exception handling into my project! Here’s the quick steps to getting NLog installed and writing records to a database.
NLog is a free logging platform for .NET, Silverlight and Windows Phone with rich log routing and management capabilities. It makes it easy to produce and manage high-quality logs for your application regardless of its size or complexity.
Create a table with the following schema, logging.sql
/****** Object: Table [dbo].[Logging] ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Logging]( [LoggingId] [uniqueidentifier] ROWGUIDCOL NOT NULL, [Date] [datetime] NULL, [Application] [varchar](200) NULL, [Level] [varchar](100) NULL, [Logger] [varchar](8000) NULL, [Message] [varchar](8000) NULL, [MachineName] [varchar](8000) NULL, [UserName] [varchar](8000) NULL, [CallSite] [varchar](8000) NULL, [Thread] [varchar](100) NULL, [Exception] [varchar](8000) NULL, [Stacktrace] [varchar](8000) NULL, CONSTRAINT [PK_logging] PRIMARY KEY CLUSTERED ( [LoggingId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[Logging] ADD CONSTRAINT [DF_Logging_LoggingId] DEFAULT (newid()) FOR [LoggingId] GO ALTER TABLE [dbo].[Logging] ADD CONSTRAINT [DF_Logging_date] DEFAULT (getdate()) FOR [Date] GO
Using Nuget, you can nuget the NLOG configuration as a starter, but here’s how it should look inserting into the newly created logging table. In NLog.config,
Data Source=.;Initial Catalog=databasename;User Id=user;Password=pass; INSERT INTO Logging(Level,Logger,Message,MachineName, UserName, CallSite, Thread, Exception, Stacktrace) VALUES (@level, @logger, @message,@machinename, @user_name, @call_site, @threadid, @log_exception, @stacktrace);
Then to start logging with NLog, simply add the following snippet of code into a class’s properties and you’re set. You can call the logger’s functions to log errors, warnings, trace, etc. Then right click on the missing Logger class and have Visual Studio resolve your missing NLog references.
private static Logger logger = LogManager.GetCurrentClassLogger();
Here is a list of the hierarchy of NLog’s logs through errors. This is important to note when you’re setting up your config.
- Trace - very detailed logs, which may include high-volume information such as protocol payloads. This log level is typically only enabled during development
- Debug - debugging information, less detailed than trace, typically not enabled in production environment.
- Info - information messages, which are normally enabled in production environment
- Warn - warning messages, typically for non-critical issues, which can be recovered or which are temporary failures
- Error - error messages
- Fatal - very serious errors