Configure database logging to file

This commit is contained in:
Matt Low 2024-09-30 15:12:56 +00:00
parent ce7b07ad95
commit a441866f2f

View File

@ -1,10 +1,14 @@
package lmcli package lmcli
import ( import (
"errors"
"fmt" "fmt"
"io/fs"
"log"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"time"
"git.mlow.ca/mlow/lmcli/pkg/agents" "git.mlow.ca/mlow/lmcli/pkg/agents"
"git.mlow.ca/mlow/lmcli/pkg/api" "git.mlow.ca/mlow/lmcli/pkg/api"
@ -16,6 +20,7 @@ import (
"git.mlow.ca/mlow/lmcli/pkg/util/tty" "git.mlow.ca/mlow/lmcli/pkg/util/tty"
"gorm.io/driver/sqlite" "gorm.io/driver/sqlite"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/logger"
) )
type Agent struct { type Agent struct {
@ -38,9 +43,45 @@ func NewContext() (*Context, error) {
return nil, err 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") 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{ 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 { if err != nil {
return nil, fmt.Errorf("Error establishing connection to store: %v", err) return nil, fmt.Errorf("Error establishing connection to store: %v", err)
@ -49,10 +90,7 @@ func NewContext() (*Context, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
return store, nil
chroma := tty.NewChromaHighlighter("markdown", *config.Chroma.Formatter, *config.Chroma.Style)
return &Context{*config, store, chroma}, nil
} }
func (c *Context) GetModels() (models []string) { func (c *Context) GetModels() (models []string) {