65.9K
CodeProject is changing. Read more.
Home

Database Logging in .NET

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.69/5 (4 votes)

Jan 12, 2004

1 min read

viewsIcon

59881

downloadIcon

906

Component that caches updates to a log and then persists them to a database on a timed interval.

Introduction

Often times, in a hosted environment, logging to a local file or the Event Log is not an option for the developer. To solve this problem, one requires a logging solution built on a database table. However, if the volume of log updates is large and frequent, posting a command to the database for each log entry is not favorable.

To overcome this, you can use the in-memory DataTable class provided by the .NET Framework. The Logger class simply encapsulates the ability to post updates to an in-memory table and then have those updates posted in batch mode to the database on some predefined interval.

Usage

To use the Logger component, add it to the form that needs the logging functionality. Also a DataTable (or DataSet) component and a corresponding SqlDataAdapter component. Assign the table that will hold the cached version of your log writes, to the ActiveTable property of the Logger and assign the adapter to the Adapter property. The default flush time is 15 minutes, which you can change to meet your environment's needs.

Somewhere in your code (like in the application's initialization), set the Enabled property of the Logger to true. Then, for each time you want to send an entry to the log, just call the Write method.