Skip to content

Commit ce2b1c2

Browse files
committed
Switch to Microsoft.Extensions.Logging
Closes #1184
1 parent 88265db commit ce2b1c2

40 files changed

+1365
-1671
lines changed

doc/logging.md

Lines changed: 5 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -1,95 +1,19 @@
11
# Logging
22

3-
Npgsql includes a built-in feature for outputting logging events which can help debug issues.
3+
Npgsql uses Microsoft.Extensions.Logging to emit log events that can be routed to your logging library of choice - see [their docs](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging) for more information. Note that Microsoft.Extensions.Logging support replaced Npgsql's own custom logging wrapper in 3.2.
44

5-
Npgsql logging is disabled by default and must be turned on. Logging can be turned on by setting `NpgsqlLogManager.Provider` to a class implementing the `INpgsqlLoggingProvider` interface. Npgsql comes with a console implementation which can be set up as follows:
5+
Since Npgsql is an ADO.NET provider and does not support dependency injection, you must manually inject your ILoggingFactory by including the following code *before* starting to use any of Npgsql's other APIs:
66

77
```c#
8-
NpgsqlLogManager.Provider = new ???
8+
NpgsqlLogManager.Provider = new LoggerFactory
9+
.AddConsole((text, logLevel) => logLevel >= LogLevel.Debug);
910
```
1011

11-
*Note: you must set the logging provider before invoking any other Npgsql method, at the very start of your program.*
12-
13-
It's trivial to create a logging provider that passes log messages to whatever logging framework you use. You can find such an adaptor for NLog [here](http://ni).
14-
15-
*Note:* the logging API is a first implementation and will probably improve/change - don't treat it as a stable part of the Npgsql API. Let us know if you think there are any missing messages or features!
16-
17-
## ConsoleLoggingProvider
18-
19-
Npgsql comes with one built-in logging provider: ConsoleLoggingProvider. It will simply dump all log messages with a given level or above to stdanrd output.
20-
You can set it up by including the following line at the beginning of your application:
21-
22-
```c#
23-
NpgsqlLogManager.Provider = new ConsoleLoggingProvider(<min level>, <print level?>, <print connector id?>);
24-
```
25-
26-
Level defaults to `NpgsqlLogLevel.Info` (which will only print warnings and errors).
27-
You can also have log levels and connector IDs logged.
12+
This will make Npgsql log to the console, for messages of at least Debug level. Other providers exist for NLog and other logging packages and services.
2813

2914
## Statement and Parameter Logging
3015

3116
Npgsql will log all SQL statements at level Debug, this can help you debug exactly what's being sent to PostgreSQL.
3217

3318
By default, Npgsql will not log parameter values as these may contain sensitive information. You can turn on
3419
parameter logging by setting `NpgsqlLogManager.IsParameterLoggingEnabled` to true.
35-
36-
## NLogLoggingProvider (or implementing your own)
37-
38-
The following provider is used in the Npgsql unit tests to pass log messages to [NLog](http://nlog-project.org/).
39-
You're welcome to copy-paste it into your project, or to use it as a starting point for implementing your own custom provider.
40-
41-
```c#
42-
class NLogLoggingProvider : INpgsqlLoggingProvider
43-
{
44-
public NpgsqlLogger CreateLogger(string name)
45-
{
46-
return new NLogLogger(name);
47-
}
48-
}
49-
50-
class NLogLogger : NpgsqlLogger
51-
{
52-
readonly Logger _log;
53-
54-
internal NLogLogger(string name)
55-
{
56-
_log = LogManager.GetLogger(name);
57-
}
58-
59-
public override bool IsEnabled(NpgsqlLogLevel level)
60-
{
61-
return _log.IsEnabled(ToNLogLogLevel(level));
62-
}
63-
64-
public override void Log(NpgsqlLogLevel level, int connectorId, string msg, Exception exception = null)
65-
{
66-
var ev = new LogEventInfo(ToNLogLogLevel(level), "", msg);
67-
if (exception != null)
68-
ev.Exception = exception;
69-
if (connectorId != 0)
70-
ev.Properties["ConnectorId"] = connectorId;
71-
_log.Log(ev);
72-
}
73-
74-
static LogLevel ToNLogLogLevel(NpgsqlLogLevel level)
75-
{
76-
switch (level)
77-
{
78-
case NpgsqlLogLevel.Trace:
79-
return LogLevel.Trace;
80-
case NpgsqlLogLevel.Debug:
81-
return LogLevel.Debug;
82-
case NpgsqlLogLevel.Info:
83-
return LogLevel.Info;
84-
case NpgsqlLogLevel.Warn:
85-
return LogLevel.Warn;
86-
case NpgsqlLogLevel.Error:
87-
return LogLevel.Error;
88-
case NpgsqlLogLevel.Fatal:
89-
return LogLevel.Fatal;
90-
default:
91-
throw new ArgumentOutOfRangeException("level");
92-
}
93-
}
94-
}
95-
```

src/Npgsql/BackendMessages/CommandCompleteMessage.cs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
2222
#endregion
2323

24+
using Microsoft.Extensions.Logging;
2425
using Npgsql.Logging;
2526

2627
namespace Npgsql.BackendMessages
@@ -31,8 +32,6 @@ class CommandCompleteMessage : IBackendMessage
3132
internal uint OID { get; private set; }
3233
internal uint Rows { get; private set; }
3334

34-
static readonly NpgsqlLogger Log = NpgsqlLogManager.GetCurrentClassLogger();
35-
3635
internal CommandCompleteMessage Load(ReadBuffer buf, int len)
3736
{
3837
Rows = 0;
@@ -54,7 +53,7 @@ internal CommandCompleteMessage Load(ReadBuffer buf, int len)
5453
if (uint.TryParse(tokens[1], out oid))
5554
OID = oid;
5655
else
57-
Log.Error("Ignoring unparseable OID in CommandComplete: " + tokens[1]);
56+
Log.Logger.LogError("Ignoring unparseable OID in CommandComplete: " + tokens[1]);
5857

5958
ParseRows(tokens[2]);
6059
break;
@@ -114,7 +113,7 @@ void ParseRows(string token)
114113
if (uint.TryParse(token, out rows))
115114
Rows = rows;
116115
else
117-
Log.Error("Ignoring unparseable rows in CommandComplete: " + token);
116+
Log.Logger.LogWarning("Ignoring unparseable rows in CommandComplete: " + token);
118117
}
119118

120119
public BackendMessageCode Code => BackendMessageCode.CompletedResponse;

src/Npgsql/BackendMessages/ErrorOrNoticeMessage.cs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#endregion
2323

2424
using System;
25+
using Microsoft.Extensions.Logging;
2526
using Npgsql.Logging;
2627
#if NET45 || NET451
2728
using System.Runtime.Serialization;
@@ -34,8 +35,6 @@ namespace Npgsql.BackendMessages
3435
#endif
3536
class ErrorOrNoticeMessage
3637
{
37-
static readonly NpgsqlLogger Log = NpgsqlLogManager.GetCurrentClassLogger();
38-
3938
internal string Severity { get; private set; }
4039
internal string Code { get; private set; }
4140
internal string Message { get; private set; }
@@ -83,7 +82,7 @@ internal ErrorOrNoticeMessage(ReadBuffer buf)
8382
var positionStr = buf.ReadNullTerminatedString();
8483
int position;
8584
if (!int.TryParse(positionStr, out position)) {
86-
Log.Warn("Non-numeric position in ErrorResponse: " + positionStr);
85+
Log.Logger.LogWarning("Non-numeric position in ErrorResponse: " + positionStr);
8786
continue;
8887
}
8988
Position = position;
@@ -92,7 +91,7 @@ internal ErrorOrNoticeMessage(ReadBuffer buf)
9291
var internalPositionStr = buf.ReadNullTerminatedString();
9392
int internalPosition;
9493
if (!Int32.TryParse(internalPositionStr, out internalPosition)) {
95-
Log.Warn("Non-numeric position in ErrorResponse: " + internalPositionStr);
94+
Log.Logger.LogWarning("Non-numeric position in ErrorResponse: " + internalPositionStr);
9695
continue;
9796
}
9897
InternalPosition = internalPosition;

src/Npgsql/Counters.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
using System.Linq;
44
using System.Reflection;
55
using JetBrains.Annotations;
6+
using Microsoft.Extensions.Logging;
7+
using Npgsql.BackendMessages;
68
using Npgsql.Logging;
79

810
namespace Npgsql
@@ -46,8 +48,6 @@ static class Counters
4648
/// </summary>
4749
internal static readonly Counter SoftDisconnectsPerSecond;
4850

49-
static readonly NpgsqlLogger Log = NpgsqlLogManager.GetCurrentClassLogger();
50-
5151
static Counters()
5252
{
5353
var enabled = false;
@@ -62,7 +62,7 @@ static Counters()
6262
}
6363
catch (Exception e)
6464
{
65-
Log.Debug("Exception while checking for performance country category (counters will be disabled)", e);
65+
Log.Logger.LogDebug("Exception while checking for performance country category (counters will be disabled)", e);
6666
}
6767
#endif
6868

0 commit comments

Comments
 (0)