Improve log display, use a <pre> so it can be easily cut and pasted.

This commit is contained in:
Justin Hawkins 2021-06-03 19:36:48 +09:30
parent b69cdebf3b
commit fdf70daba7
7 changed files with 84 additions and 64 deletions

View File

@ -2,10 +2,13 @@ package config
import ( import (
"encoding/json" "encoding/json"
"fmt"
"io/ioutil" "io/ioutil"
"log" "log"
"os" "os"
daulog "github.com/tardisx/discord-auto-upload/log"
"github.com/mitchellh/go-homedir" "github.com/mitchellh/go-homedir"
) )
@ -24,11 +27,11 @@ const CurrentVersion string = "0.8"
// Load the current config or initialise with defaults // Load the current config or initialise with defaults
func LoadOrInit() { func LoadOrInit() {
configPath := configPath() configPath := configPath()
log.Printf("Trying to load from %s\n", configPath) daulog.SendLog(fmt.Sprintf("Trying to load config from %s", configPath), daulog.LogTypeDebug)
_, err := os.Stat(configPath) _, err := os.Stat(configPath)
if os.IsNotExist(err) { if os.IsNotExist(err) {
log.Printf("NOTE: No config file, writing out sample configuration") daulog.SendLog("NOTE: No config file, writing out sample configuration", daulog.LogTypeInfo)
log.Printf("You need to set the configuration via the web interface") daulog.SendLog("You need to set the configuration via the web interface", daulog.LogTypeInfo)
Config.WebHookURL = "" Config.WebHookURL = ""
Config.Path = homeDir() + string(os.PathSeparator) + "screenshots" Config.Path = homeDir() + string(os.PathSeparator) + "screenshots"
@ -52,7 +55,7 @@ func LoadConfig() {
} }
func SaveConfig() { func SaveConfig() {
log.Print("saving configuration") daulog.SendLog("saving configuration", daulog.LogTypeInfo)
path := configPath() path := configPath()
jsonString, _ := json.Marshal(Config) jsonString, _ := json.Marshal(Config)
err := ioutil.WriteFile(path, jsonString, os.ModePerm) err := ioutil.WriteFile(path, jsonString, os.ModePerm)

View File

@ -123,10 +123,11 @@ $(document).ready(function() {
.done(function(data) { .done(function(data) {
var this_el = $(".config-item[data-key='"+key+"']").find('.rest-field'); var this_el = $(".config-item[data-key='"+key+"']").find('.rest-field');
if (this_el.hasClass('rest-field-boolean')) { if (this_el.hasClass('rest-field-boolean')) {
this_el.prop('checked', data.Value); this_el.prop('checked', data.value);
} }
else { else {
this_el.val(data.Value);
this_el.val(data.value);
} }
update_sadness(); update_sadness();
@ -142,7 +143,7 @@ $(document).ready(function() {
} }
$.post('/rest/config/'+key, { value: val }) $.post('/rest/config/'+key, { value: val })
.done(function(d) { .done(function(d) {
if (d.Success) { if (d.success) {
alert('Updated config'); alert('Updated config');
} else { } else {
alert("Error: " + d.Error); alert("Error: " + d.Error);

View File

@ -42,6 +42,10 @@ body {
max-width: 42em; max-width: 42em;
} }
pre {
background-color: black;
color: aliceblue;
}
/* /*
* Header * Header

View File

@ -3,17 +3,8 @@
<h1 class="DAU-heading">Config</h1> <h1 class="DAU-heading">Config</h1>
<p class="lead">Discord-auto-upload logs</p> <p class="lead">Discord-auto-upload logs</p>
<table class="table table-condensed"> <pre id="logs" class="text-left pre-scrollable">
<thead> </pre>
<tr>
<th>time</th><th>entry</th>
</tr>
</thead>
<tbody id="logs">
</tbody>
</table>
</main> </main>
<script> <script>
@ -21,15 +12,7 @@ $(document).ready(function() {
$.ajax({ method: 'get', url: '/rest/logs'}) $.ajax({ method: 'get', url: '/rest/logs'})
.done(function(data) { .done(function(data) {
console.log(data); console.log(data);
$.each(data, function(i, d) { $('#logs').text(data);
console.log('do', d);
$('#logs').append(
$('<tr>').append(
$('<th>').text(d.ts),
$('<td>').text(d.log)
)
);
});
}); });
}); });
</script> </script>

28
dau.go
View File

@ -29,6 +29,7 @@ import (
"golang.org/x/image/font/inconsolata" "golang.org/x/image/font/inconsolata"
"github.com/tardisx/discord-auto-upload/config" "github.com/tardisx/discord-auto-upload/config"
daulog "github.com/tardisx/discord-auto-upload/log"
"github.com/tardisx/discord-auto-upload/web" "github.com/tardisx/discord-auto-upload/web"
) )
@ -45,7 +46,7 @@ func main() {
checkUpdates() checkUpdates()
sendLogToWeb(fmt.Sprintf("Waiting for images to appear in %s", config.Config.Path)) daulog.SendLog(fmt.Sprintf("Waiting for images to appear in %s", config.Config.Path), daulog.LogTypeInfo)
// wander the path, forever // wander the path, forever
for { for {
if checkPath(config.Config.Path) { if checkPath(config.Config.Path) {
@ -56,7 +57,7 @@ func main() {
} }
lastCheck = newLastCheck lastCheck = newLastCheck
} }
sendLogToWeb(fmt.Sprintf("sleeping for %ds before next check of %s", config.Config.Watch, config.Config.Path)) daulog.SendLog(fmt.Sprintf("sleeping for %ds before next check of %s", config.Config.Watch, config.Config.Path), daulog.LogTypeDebug)
time.Sleep(time.Duration(config.Config.Watch) * time.Second) time.Sleep(time.Duration(config.Config.Watch) * time.Second)
} }
} }
@ -83,12 +84,12 @@ func checkUpdates() {
Body string Body string
} }
sendLogToWeb("checking for new version") daulog.SendLog("checking for new version", daulog.LogTypeInfo)
client := &http.Client{Timeout: time.Second * 5} client := &http.Client{Timeout: time.Second * 5}
resp, err := client.Get("https://api.github.com/repos/tardisx/discord-auto-upload/releases/latest") resp, err := client.Get("https://api.github.com/repos/tardisx/discord-auto-upload/releases/latest")
if err != nil { if err != nil {
sendLogToWeb(fmt.Sprintf("WARNING: Update check failed: %v", err)) daulog.SendLog(fmt.Sprintf("WARNING: Update check failed: %v", err), daulog.LogTypeError)
return return
} }
defer resp.Body.Close() defer resp.Body.Close()
@ -110,7 +111,7 @@ func checkUpdates() {
fmt.Println(latest.Body) fmt.Println(latest.Body)
fmt.Println("------------------------------------") fmt.Println("------------------------------------")
fmt.Println("Upgrade at https://github.com/tardisx/discord-auto-upload/releases/latest") fmt.Println("Upgrade at https://github.com/tardisx/discord-auto-upload/releases/latest")
sendLogToWeb(fmt.Sprintf("New version available: %s - download at https://github.com/tardisx/discord-auto-upload/releases/latest")) daulog.SendLog(fmt.Sprintf("New version available: %s - download at https://github.com/tardisx/discord-auto-upload/releases/latest"), daulog.LogTypeInfo)
} }
} }
@ -155,13 +156,6 @@ func checkFile(path string, f os.FileInfo, err error) error {
return nil return nil
} }
func sendLogToWeb(entry string) {
web.LogInput <- web.LogEntry{
Timestamp: time.Now(),
Entry: entry,
}
}
func fileEligible(file string) bool { func fileEligible(file string) bool {
if config.Config.Exclude != "" && strings.Contains(file, config.Config.Exclude) { if config.Config.Exclude != "" && strings.Contains(file, config.Config.Exclude) {
@ -179,16 +173,16 @@ func fileEligible(file string) bool {
func processFile(file string) { func processFile(file string) {
if !config.Config.NoWatermark { if !config.Config.NoWatermark {
sendLogToWeb("Copying to temp location and watermarking ") daulog.SendLog("Copying to temp location and watermarking ", daulog.LogTypeInfo)
file = mungeFile(file) file = mungeFile(file)
} }
if config.Config.WebHookURL == "" { if config.Config.WebHookURL == "" {
sendLogToWeb("WebHookURL is not configured - cannot upload!") daulog.SendLog("WebHookURL is not configured - cannot upload!", daulog.LogTypeError)
return return
} }
sendLogToWeb("Uploading") daulog.SendLog("Uploading", daulog.LogTypeInfo)
extraParams := map[string]string{} extraParams := map[string]string{}
@ -274,7 +268,7 @@ func processFile(file string) {
} }
if !config.Config.NoWatermark { if !config.Config.NoWatermark {
sendLogToWeb(fmt.Sprintf("Removing temporary file: %s", file)) daulog.SendLog(fmt.Sprintf("Removing temporary file: %s", file), daulog.LogTypeDebug)
os.Remove(file) os.Remove(file)
} }
@ -288,7 +282,7 @@ func sleepForRetries(retry int) {
return return
} }
retryTime := (6-retry)*(6-retry) + 6 retryTime := (6-retry)*(6-retry) + 6
sendLogToWeb(fmt.Sprintf("Will retry in %d seconds (%d remaining attempts)", retryTime, retry)) daulog.SendLog(fmt.Sprintf("Will retry in %d seconds (%d remaining attempts)", retryTime, retry), daulog.LogTypeError)
time.Sleep(time.Duration(retryTime) * time.Second) time.Sleep(time.Duration(retryTime) * time.Second)
} }

42
log/log.go Normal file
View File

@ -0,0 +1,42 @@
package log
import (
"time"
)
type LogEntryType string
type LogEntry struct {
Timestamp time.Time `json:"ts"`
Type LogEntryType `json:"type"`
Entry string `json:"log"`
}
const (
LogTypeInfo = "info"
LogTypeError = "error"
LogTypeDebug = "debug"
)
var LogEntries []LogEntry
var logInput chan LogEntry
func init() {
// wait for log entries
logInput = make(chan LogEntry)
go func() {
for {
aLog := <-logInput
LogEntries = append(LogEntries, aLog)
}
}()
}
func SendLog(entry string, entryType LogEntryType) {
logInput <- LogEntry{
Timestamp: time.Now(),
Entry: entry,
Type: entryType,
}
}

View File

@ -11,10 +11,10 @@ import (
"regexp" "regexp"
"strconv" "strconv"
"text/template" "text/template"
"time"
"github.com/tardisx/discord-auto-upload/assets" "github.com/tardisx/discord-auto-upload/assets"
"github.com/tardisx/discord-auto-upload/config" "github.com/tardisx/discord-auto-upload/config"
daulog "github.com/tardisx/discord-auto-upload/log"
) )
// DAUWebServer - stuff for the web server // DAUWebServer - stuff for the web server
@ -37,14 +37,6 @@ type errorResponse struct {
Error string `json:"error"` Error string `json:"error"`
} }
type LogEntry struct {
Timestamp time.Time `json:"ts"`
Entry string `json:"log"`
}
var logEntries []LogEntry
var LogInput chan LogEntry
func getStatic(w http.ResponseWriter, r *http.Request) { func getStatic(w http.ResponseWriter, r *http.Request) {
// haha this is dumb and I should change it // haha this is dumb and I should change it
re := regexp.MustCompile(`[^a-zA-Z0-9\.]`) re := regexp.MustCompile(`[^a-zA-Z0-9\.]`)
@ -280,20 +272,21 @@ func getSetExclude(w http.ResponseWriter, r *http.Request) {
} }
func getLogs(w http.ResponseWriter, r *http.Request) { func getLogs(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "text/plain")
js, _ := json.Marshal(logEntries)
w.Write(js) text := ""
for _, log := range daulog.LogEntries {
text = text + fmt.Sprintf(
"%-6s %-19s %s\n", log.Type, log.Timestamp.Format("2006-01-02 15:04:05"), log.Entry,
)
}
// js, _ := json.Marshal(daulog.LogEntries)
w.Write([]byte(text))
} }
func StartWebServer() { func StartWebServer() {
// wait for log entries
LogInput = make(chan LogEntry)
go func() {
for {
aLog := <-LogInput
logEntries = append(logEntries, aLog)
}
}()
http.HandleFunc("/", getStatic) http.HandleFunc("/", getStatic)
http.HandleFunc("/rest/config/webhook", getSetWebhook) http.HandleFunc("/rest/config/webhook", getSetWebhook)