gpt4 book ai didi

.net - Dapper 和 Postgres - 打印查询

转载 作者:行者123 更新时间:2023-12-02 05:17:17 26 4
gpt4 key购买 nike

我将 Dapper 与 Postgres 一起使用,我想记录一些诊断信息,尤其是正在运行的实际查询。

如果我使用 SQL Server,我会这样做

let connection = new SqlConnection(connectionString)
connection.StatisticsEnabled = true

// run query

let stats = connection.RetrieveStatistics()

但我似乎找不到类似的东西 NpgsqlConnection

检索为 NpgsqlConnection 运行的实际查询的最佳方法是什么?

最佳答案

我能够通过创建 NpgSql 日志记录提供程序来打印查询,如所述 here .

type SqlLogger (logger: ILogger) =

inherit NpgsqlLogger() with

let mapLogLevel level =
match level with
| NpgsqlLogLevel.Trace -> LogLevel.Debug
| NpgsqlLogLevel.Debug -> LogLevel.Debug
| NpgsqlLogLevel.Info -> LogLevel.Information
| NpgsqlLogLevel.Warn -> LogLevel.Warning
| NpgsqlLogLevel.Error -> LogLevel.Error
| NpgsqlLogLevel.Fatal -> LogLevel.Critical
| _ -> LogLevel.Debug


override __.IsEnabled(_level : NpgsqlLogLevel) = true
override __.Log(level, connectorId, msg, ex) =
let level = mapLogLevel level
logger.Log(level, ex, msg)


type SqlLoggerProvider (loggerFactory: ILoggerFactory ) =
member __.loggerFactory = loggerFactory
interface INpgsqlLoggingProvider with
member __.CreateLogger(name) = loggerFactory.CreateLogger(name) |> SqlLogger :> NpgsqlLogger

然后像这样注册它:

let configureApp (app : IApplicationBuilder) =    
NpgsqlLogManager.Provider <- SqlLoggerProvider (app.ApplicationServices.GetService<ILoggerFactory>())
NpgsqlLogManager.IsParameterLoggingEnabled <- true

关于.net - Dapper 和 Postgres - 打印查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57553298/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com