From a441866f2fe16b2583bb0435670649fee611015e Mon Sep 17 00:00:00 2001 From: Matt Low Date: Mon, 30 Sep 2024 15:12:56 +0000 Subject: [PATCH] Configure database logging to file --- pkg/lmcli/lmcli.go | 48 +++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/pkg/lmcli/lmcli.go b/pkg/lmcli/lmcli.go index 1f0b565..e75bc2a 100644 --- a/pkg/lmcli/lmcli.go +++ b/pkg/lmcli/lmcli.go @@ -1,10 +1,14 @@ package lmcli import ( + "errors" "fmt" + "io/fs" + "log" "os" "path/filepath" "strings" + "time" "git.mlow.ca/mlow/lmcli/pkg/agents" "git.mlow.ca/mlow/lmcli/pkg/api" @@ -16,6 +20,7 @@ import ( "git.mlow.ca/mlow/lmcli/pkg/util/tty" "gorm.io/driver/sqlite" "gorm.io/gorm" + "gorm.io/gorm/logger" ) type Agent struct { @@ -38,9 +43,45 @@ func NewContext() (*Context, error) { return nil, err } + store, err := getConversationStore() + if err != nil { + return nil, err + } + + chroma := tty.NewChromaHighlighter("markdown", *config.Chroma.Formatter, *config.Chroma.Style) + return &Context{*config, store, chroma}, nil +} + +func createOrOpenAppend(path string) (*os.File, error) { + var file *os.File + if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) { + file, err = os.Create(path) + if err != nil { + return nil, err + } + } else { + file, err = os.OpenFile(path, os.O_APPEND, fs.ModeAppend) + if err != nil { + return nil, err + } + } + return file, nil +} + +func getConversationStore() (ConversationStore, error) { databaseFile := filepath.Join(dataDir(), "conversations.db") + + gormLogFile, err := createOrOpenAppend(filepath.Join(dataDir(), "database.log")) + if err != nil { + return nil, fmt.Errorf("Could not open database log file: %v", err) + } db, err := gorm.Open(sqlite.Open(databaseFile), &gorm.Config{ - //Logger: logger.Default.LogMode(logger.Info), + Logger: logger.New(log.New(gormLogFile, "", log.LstdFlags), logger.Config{ + SlowThreshold: 200 * time.Millisecond, + LogLevel: logger.Warn, + IgnoreRecordNotFoundError: false, + Colorful: true, + }), }) if err != nil { return nil, fmt.Errorf("Error establishing connection to store: %v", err) @@ -49,10 +90,7 @@ func NewContext() (*Context, error) { if err != nil { return nil, err } - - chroma := tty.NewChromaHighlighter("markdown", *config.Chroma.Formatter, *config.Chroma.Style) - - return &Context{*config, store, chroma}, nil + return store, nil } func (c *Context) GetModels() (models []string) {