Add logging control

This commit is contained in:
Julien Riou 2018-06-24 17:49:48 +02:00
parent 96ade1c1d7
commit f0d3cd5bdf
No known key found for this signature in database
GPG key ID: BA3E15176E45E85D
9 changed files with 164 additions and 24 deletions

View file

@ -2,9 +2,9 @@ package base
import (
"fmt"
"github.com/jouir/pgterminate/log"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
"path/filepath"
"strings"
"sync"
@ -64,7 +64,7 @@ func (c *Config) Read(file string) error {
// Reload reads from file and update configuration
func (c *Config) Reload() {
log.Println("Reloading configuration")
log.Debug("Reloading configuration")
c.mutex.Lock()
defer c.mutex.Unlock()
if c.File != "" {

View file

@ -2,8 +2,9 @@ package base
import (
"database/sql"
"fmt"
"github.com/jouir/pgterminate/log"
"github.com/lib/pq"
"strconv"
)
const (
@ -42,7 +43,15 @@ func (db *Db) Disconnect() {
// Sessions connects to the database and returns current sessions
func (db *Db) Sessions() (sessions []Session) {
query := `select pid as pid, usename as user, datname as db, host(client_addr)::text || ':' || client_port::text as client, state as state, substring(query from 1 for ` + strconv.Itoa(maxQueryLength) + `) as query, coalesce(extract(epoch from now() - state_change), 0) as "stateDuration" from pg_catalog.pg_stat_activity where pid <> pg_backend_pid();`
query := fmt.Sprintf(`select pid as pid,
usename as user,
datname as db,
host(client_addr)::text || ':' || client_port::text as client,
state as state, substring(query from 1 for %d) as query,
coalesce(extract(epoch from now() - state_change), 0) as "stateDuration"
from pg_catalog.pg_stat_activity
where pid <> pg_backend_pid();`, maxQueryLength)
log.Debugf("query: %s\n", query)
rows, err := db.conn.Query(query)
Panic(err)
defer rows.Close()
@ -70,6 +79,7 @@ func (db *Db) TerminateSessions(sessions []Session) {
}
if len(pids) > 0 {
query := `select pg_terminate_backend(pid) from pg_stat_activity where pid = any($1);`
log.Debugf("query: %s\n", query)
_, err := db.conn.Exec(query, pq.Array(pids))
Panic(err)
}

View file

@ -1,12 +1,12 @@
package base
import (
"log"
"github.com/jouir/pgterminate/log"
)
// Panic prints a non-nil error and terminates the program
func Panic(err error) {
if err != nil {
log.Fatalln(err)
log.Fatalf("%s\n", err)
}
}