Add logger

This commit is contained in:
Frédéric Guillot 2017-12-15 18:55:57 -08:00
parent c6d9eb3614
commit 1d8193b892
56 changed files with 228 additions and 192 deletions

View file

@ -5,12 +5,13 @@
package helper package helper
import ( import (
"log"
"time" "time"
"github.com/miniflux/miniflux/logger"
) )
// ExecutionTime returns the elapsed time of a block of code. // ExecutionTime returns the elapsed time of a block of code.
func ExecutionTime(start time.Time, name string) { func ExecutionTime(start time.Time, name string) {
elapsed := time.Since(start) elapsed := time.Since(start)
log.Printf("%s took %s", name, elapsed) logger.Debug("%s took %s", name, elapsed)
} }

View file

@ -7,12 +7,12 @@ package http
import ( import (
"crypto/tls" "crypto/tls"
"fmt" "fmt"
"log"
"net/http" "net/http"
"net/url" "net/url"
"time" "time"
"github.com/miniflux/miniflux/helper" "github.com/miniflux/miniflux/helper"
"github.com/miniflux/miniflux/logger"
) )
const userAgent = "Miniflux <https://miniflux.net/>" const userAgent = "Miniflux <https://miniflux.net/>"
@ -47,7 +47,7 @@ func (c *Client) Get() (*Response, error) {
ContentType: resp.Header.Get("Content-Type"), ContentType: resp.Header.Get("Content-Type"),
} }
log.Println("[HttpClient:Get]", logger.Debug("[HttpClient:Get]",
"OriginalURL:", c.url, "OriginalURL:", c.url,
"StatusCode:", response.StatusCode, "StatusCode:", response.StatusCode,
"ETag:", response.ETag, "ETag:", response.ETag,

View file

@ -5,10 +5,9 @@
package integration package integration
import ( import (
"log"
"github.com/miniflux/miniflux/integration/instapaper" "github.com/miniflux/miniflux/integration/instapaper"
"github.com/miniflux/miniflux/integration/pinboard" "github.com/miniflux/miniflux/integration/pinboard"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
) )
@ -18,7 +17,7 @@ func SendEntry(entry *model.Entry, integration *model.Integration) {
client := pinboard.NewClient(integration.PinboardToken) client := pinboard.NewClient(integration.PinboardToken)
err := client.AddBookmark(entry.URL, entry.Title, integration.PinboardTags, integration.PinboardMarkAsUnread) err := client.AddBookmark(entry.URL, entry.Title, integration.PinboardTags, integration.PinboardMarkAsUnread)
if err != nil { if err != nil {
log.Println("[Pinboard]", err) logger.Error("[Pinboard] %v", err)
} }
} }
@ -26,7 +25,7 @@ func SendEntry(entry *model.Entry, integration *model.Integration) {
client := instapaper.NewClient(integration.InstapaperUsername, integration.InstapaperPassword) client := instapaper.NewClient(integration.InstapaperUsername, integration.InstapaperPassword)
err := client.AddURL(entry.URL, entry.Title) err := client.AddURL(entry.URL, entry.Title)
if err != nil { if err != nil {
log.Println("[Instapaper]", err) logger.Error("[Instapaper] %v", err)
} }
} }
} }

View file

@ -4,7 +4,7 @@
package locale package locale
import "log" import "github.com/miniflux/miniflux/logger"
// Translation is the translation mapping table. // Translation is the translation mapping table.
type Translation map[string]interface{} type Translation map[string]interface{}
@ -17,7 +17,7 @@ func Load() *Translator {
translator := NewTranslator() translator := NewTranslator()
for language, tr := range translations { for language, tr := range translations {
log.Println("Loading translation:", language) logger.Debug("Loading translation: %s", language)
translator.AddLanguage(language, tr) translator.AddLanguage(language, tr)
} }

View file

@ -1,5 +1,5 @@
// Code generated by go generate; DO NOT EDIT. // Code generated by go generate; DO NOT EDIT.
// 2017-12-12 21:44:02.672642313 -0800 PST m=+0.027053016 // 2017-12-15 18:49:24.054372873 -0800 PST m=+0.026968745
package locale package locale

37
logger/logger.go Normal file
View file

@ -0,0 +1,37 @@
// Copyright 2017 Frédéric Guillot. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package logger
import (
"fmt"
"os"
"time"
)
// Debug sends a debug log message.
func Debug(format string, v ...interface{}) {
formatMessage("DEBUG", format, v...)
}
// Info sends an info log message.
func Info(format string, v ...interface{}) {
formatMessage("INFO", format, v...)
}
// Error sends an error log message.
func Error(format string, v ...interface{}) {
formatMessage("ERROR", format, v...)
}
// Fatal sends a fatal log message and stop the execution of the program.
func Fatal(format string, v ...interface{}) {
formatMessage("FATAL", format, v...)
os.Exit(1)
}
func formatMessage(level, format string, v ...interface{}) {
prefix := fmt.Sprintf("[%s] [%s] ", time.Now().Format("2006-01-02T15:04:05"), level)
fmt.Fprintf(os.Stderr, prefix+format+"\n", v...)
}

View file

@ -18,7 +18,6 @@ import (
"context" "context"
"flag" "flag"
"fmt" "fmt"
"log"
"os" "os"
"os/signal" "os/signal"
"runtime" "runtime"
@ -26,6 +25,7 @@ import (
"time" "time"
"github.com/miniflux/miniflux/config" "github.com/miniflux/miniflux/config"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/reader/feed" "github.com/miniflux/miniflux/reader/feed"
"github.com/miniflux/miniflux/scheduler" "github.com/miniflux/miniflux/scheduler"
@ -38,7 +38,7 @@ import (
) )
func run(cfg *config.Config, store *storage.Storage) { func run(cfg *config.Config, store *storage.Storage) {
log.Println("Starting Miniflux...") logger.Info("Starting Miniflux...")
stop := make(chan os.Signal, 1) stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt) signal.Notify(stop, os.Interrupt)
@ -55,11 +55,11 @@ func run(cfg *config.Config, store *storage.Storage) {
) )
<-stop <-stop
log.Println("Shutting down the server...") logger.Info("Shutting down the server...")
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second) ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
server.Shutdown(ctx) server.Shutdown(ctx)
store.Close() store.Close()
log.Println("Server gracefully stopped") logger.Info("Server gracefully stopped")
} }
func askCredentials() (string, string) { func askCredentials() (string, string) {

View file

@ -6,12 +6,12 @@ package atom
import ( import (
"encoding/xml" "encoding/xml"
"log"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/miniflux/miniflux/helper" "github.com/miniflux/miniflux/helper"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/reader/date" "github.com/miniflux/miniflux/reader/date"
"github.com/miniflux/miniflux/url" "github.com/miniflux/miniflux/url"
@ -130,7 +130,7 @@ func getDate(a *atomEntry) time.Time {
if a.Updated != "" { if a.Updated != "" {
result, err := date.Parse(a.Updated) result, err := date.Parse(a.Updated)
if err != nil { if err != nil {
log.Println(err) logger.Error("atom: %v", err)
return time.Now() return time.Now()
} }

View file

@ -6,12 +6,12 @@ package feed
import ( import (
"fmt" "fmt"
"log"
"time" "time"
"github.com/miniflux/miniflux/errors" "github.com/miniflux/miniflux/errors"
"github.com/miniflux/miniflux/helper" "github.com/miniflux/miniflux/helper"
"github.com/miniflux/miniflux/http" "github.com/miniflux/miniflux/http"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/reader/icon" "github.com/miniflux/miniflux/reader/icon"
"github.com/miniflux/miniflux/reader/processor" "github.com/miniflux/miniflux/reader/processor"
@ -80,13 +80,13 @@ func (h *Handler) CreateFeed(userID, categoryID int64, url string, crawler bool)
return nil, err return nil, err
} }
log.Println("[Handler:CreateFeed] Feed saved with ID:", subscription.ID) logger.Debug("[Handler:CreateFeed] Feed saved with ID: %d", subscription.ID)
icon, err := icon.FindIcon(subscription.SiteURL) icon, err := icon.FindIcon(subscription.SiteURL)
if err != nil { if err != nil {
log.Println(err) logger.Error("[Handler:CreateFeed] %v", err)
} else if icon == nil { } else if icon == nil {
log.Printf("No icon found for feedID=%d\n", subscription.ID) logger.Info("No icon found for feedID=%d", subscription.ID)
} else { } else {
h.store.CreateFeedIcon(subscription, icon) h.store.CreateFeedIcon(subscription, icon)
} }
@ -128,7 +128,7 @@ func (h *Handler) RefreshFeed(userID, feedID int64) error {
} }
if response.IsModified(originalFeed.EtagHeader, originalFeed.LastModifiedHeader) { if response.IsModified(originalFeed.EtagHeader, originalFeed.LastModifiedHeader) {
log.Printf("[Handler:RefreshFeed] Feed #%d has been modified\n", feedID) logger.Debug("[Handler:RefreshFeed] Feed #%d has been modified", feedID)
body, err := response.NormalizeBodyEncoding() body, err := response.NormalizeBodyEncoding()
if err != nil { if err != nil {
return errors.NewLocalizedError(errEncoding, err) return errors.NewLocalizedError(errEncoding, err)
@ -156,16 +156,16 @@ func (h *Handler) RefreshFeed(userID, feedID int64) error {
} }
if !h.store.HasIcon(originalFeed.ID) { if !h.store.HasIcon(originalFeed.ID) {
log.Println("[Handler:RefreshFeed] Looking for feed icon") logger.Debug("[Handler:RefreshFeed] Looking for feed icon")
icon, err := icon.FindIcon(originalFeed.SiteURL) icon, err := icon.FindIcon(originalFeed.SiteURL)
if err != nil { if err != nil {
log.Println("[Handler:RefreshFeed]", err) logger.Error("[Handler:RefreshFeed] %v", err)
} else { } else {
h.store.CreateFeedIcon(originalFeed, icon) h.store.CreateFeedIcon(originalFeed, icon)
} }
} }
} else { } else {
log.Printf("[Handler:RefreshFeed] Feed #%d not modified\n", feedID) logger.Debug("[Handler:RefreshFeed] Feed #%d not modified", feedID)
} }
originalFeed.ParsingErrorCount = 0 originalFeed.ParsingErrorCount = 0

View file

@ -8,10 +8,10 @@ import (
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"log"
"github.com/miniflux/miniflux/helper" "github.com/miniflux/miniflux/helper"
"github.com/miniflux/miniflux/http" "github.com/miniflux/miniflux/http"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/url" "github.com/miniflux/miniflux/url"
@ -36,7 +36,7 @@ func FindIcon(websiteURL string) (*model.Icon, error) {
return nil, err return nil, err
} }
log.Println("[FindIcon] Fetching icon =>", iconURL) logger.Debug("[FindIcon] Fetching icon => %s", iconURL)
icon, err := downloadIcon(iconURL) icon, err := downloadIcon(iconURL)
if err != nil { if err != nil {
return nil, err return nil, err

View file

@ -5,11 +5,11 @@
package json package json
import ( import (
"log"
"strings" "strings"
"time" "time"
"github.com/miniflux/miniflux/helper" "github.com/miniflux/miniflux/helper"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/reader/date" "github.com/miniflux/miniflux/reader/date"
"github.com/miniflux/miniflux/reader/sanitizer" "github.com/miniflux/miniflux/reader/sanitizer"
@ -87,7 +87,7 @@ func (j *jsonItem) GetDate() time.Time {
if value != "" { if value != "" {
d, err := date.Parse(value) d, err := date.Parse(value)
if err != nil { if err != nil {
log.Println(err) logger.Error("json: %v", err)
return time.Now() return time.Now()
} }

View file

@ -8,8 +8,8 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"log"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/storage" "github.com/miniflux/miniflux/storage"
) )
@ -23,7 +23,7 @@ type Handler struct {
func (h *Handler) Export(userID int64) (string, error) { func (h *Handler) Export(userID int64) (string, error) {
feeds, err := h.store.Feeds(userID) feeds, err := h.store.Feeds(userID)
if err != nil { if err != nil {
log.Println(err) logger.Error("[OPML:Export] %v", err)
return "", errors.New("unable to fetch feeds") return "", errors.New("unable to fetch feeds")
} }
@ -54,13 +54,13 @@ func (h *Handler) Import(userID int64, data io.Reader) (err error) {
if subscription.CategoryName == "" { if subscription.CategoryName == "" {
category, err = h.store.FirstCategory(userID) category, err = h.store.FirstCategory(userID)
if err != nil { if err != nil {
log.Println(err) logger.Error("[OPML:Import] %v", err)
return errors.New("unable to find first category") return errors.New("unable to find first category")
} }
} else { } else {
category, err = h.store.CategoryByTitle(userID, subscription.CategoryName) category, err = h.store.CategoryByTitle(userID, subscription.CategoryName)
if err != nil { if err != nil {
log.Println(err) logger.Error("[OPML:Import] %v", err)
return errors.New("unable to search category by title") return errors.New("unable to search category by title")
} }
@ -72,7 +72,7 @@ func (h *Handler) Import(userID int64, data io.Reader) (err error) {
err := h.store.CreateCategory(category) err := h.store.CreateCategory(category)
if err != nil { if err != nil {
log.Println(err) logger.Error("[OPML:Import] %v", err)
return fmt.Errorf(`unable to create this category: "%s"`, subscription.CategoryName) return fmt.Errorf(`unable to create this category: "%s"`, subscription.CategoryName)
} }
} }

View file

@ -8,7 +8,8 @@ import (
"bufio" "bufio"
"bytes" "bytes"
"encoding/xml" "encoding/xml"
"log"
"github.com/miniflux/miniflux/logger"
) )
// Serialize returns a SubcriptionList in OPML format. // Serialize returns a SubcriptionList in OPML format.
@ -37,7 +38,7 @@ func Serialize(subscriptions SubcriptionList) string {
encoder := xml.NewEncoder(writer) encoder := xml.NewEncoder(writer)
encoder.Indent(" ", " ") encoder.Indent(" ", " ")
if err := encoder.Encode(feeds); err != nil { if err := encoder.Encode(feeds); err != nil {
log.Println(err) logger.Error("[OPML:Serialize] %v", err)
return "" return ""
} }

View file

@ -5,8 +5,7 @@
package processor package processor
import ( import (
"log" "github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/reader/rewrite" "github.com/miniflux/miniflux/reader/rewrite"
"github.com/miniflux/miniflux/reader/sanitizer" "github.com/miniflux/miniflux/reader/sanitizer"
@ -42,7 +41,7 @@ func (f *FeedProcessor) Process() {
if f.crawler { if f.crawler {
content, err := scraper.Fetch(entry.URL, f.scraperRules) content, err := scraper.Fetch(entry.URL, f.scraperRules)
if err != nil { if err != nil {
log.Println("[FeedProcessor]", err) logger.Error("[FeedProcessor] %v", err)
} else { } else {
entry.Content = content entry.Content = content
} }

View file

@ -8,12 +8,12 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"log"
"math" "math"
"regexp" "regexp"
"strings" "strings"
"github.com/PuerkitoBio/goquery" "github.com/PuerkitoBio/goquery"
"github.com/miniflux/miniflux/logger"
"golang.org/x/net/html" "golang.org/x/net/html"
) )
@ -83,10 +83,10 @@ func ExtractContent(page io.Reader) (string, error) {
removeUnlikelyCandidates(document) removeUnlikelyCandidates(document)
candidates := getCandidates(document) candidates := getCandidates(document)
log.Println("Candidates:", candidates) logger.Debug("[Readability] Candidates: %v", candidates)
topCandidate := getTopCandidate(document, candidates) topCandidate := getTopCandidate(document, candidates)
log.Println("TopCandidate:", topCandidate) logger.Debug("[Readability] TopCandidate: %v", topCandidate)
output := getArticle(topCandidate, candidates) output := getArticle(topCandidate, candidates)
return output, nil return output, nil
@ -142,7 +142,6 @@ func removeUnlikelyCandidates(document *goquery.Document) {
str := class + id str := class + id
if blacklistCandidatesRegexp.MatchString(str) || (unlikelyCandidatesRegexp.MatchString(str) && !okMaybeItsACandidateRegexp.MatchString(str)) { if blacklistCandidatesRegexp.MatchString(str) || (unlikelyCandidatesRegexp.MatchString(str) && !okMaybeItsACandidateRegexp.MatchString(str)) {
// log.Printf("Removing unlikely candidate - %s\n", str)
removeNodes(s) removeNodes(s)
} }
}) })

View file

@ -6,13 +6,13 @@ package rss
import ( import (
"encoding/xml" "encoding/xml"
"log"
"path" "path"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/miniflux/miniflux/helper" "github.com/miniflux/miniflux/helper"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/reader/date" "github.com/miniflux/miniflux/reader/date"
"github.com/miniflux/miniflux/url" "github.com/miniflux/miniflux/url"
@ -130,7 +130,7 @@ func (r *rssItem) GetDate() time.Time {
if value != "" { if value != "" {
result, err := date.Parse(value) result, err := date.Parse(value)
if err != nil { if err != nil {
log.Println(err) logger.Error("rss: %v", err)
return time.Now() return time.Now()
} }

View file

@ -7,11 +7,11 @@ package scraper
import ( import (
"errors" "errors"
"io" "io"
"log"
"strings" "strings"
"github.com/PuerkitoBio/goquery" "github.com/PuerkitoBio/goquery"
"github.com/miniflux/miniflux/http" "github.com/miniflux/miniflux/http"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/reader/readability" "github.com/miniflux/miniflux/reader/readability"
"github.com/miniflux/miniflux/url" "github.com/miniflux/miniflux/url"
) )
@ -42,10 +42,10 @@ func Fetch(websiteURL, rules string) (string, error) {
var content string var content string
if rules != "" { if rules != "" {
log.Printf(`[Scraper] Using rules "%s" for "%s"`, rules, websiteURL) logger.Debug(`[Scraper] Using rules "%s" for "%s"`, rules, websiteURL)
content, err = scrapContent(page, rules) content, err = scrapContent(page, rules)
} else { } else {
log.Printf(`[Scraper] Using readability for "%s"`, websiteURL) logger.Debug(`[Scraper] Using readability for "%s"`, websiteURL)
content, err = readability.ExtractContent(page) content, err = readability.ExtractContent(page)
} }

View file

@ -8,12 +8,12 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"log"
"time" "time"
"github.com/miniflux/miniflux/errors" "github.com/miniflux/miniflux/errors"
"github.com/miniflux/miniflux/helper" "github.com/miniflux/miniflux/helper"
"github.com/miniflux/miniflux/http" "github.com/miniflux/miniflux/http"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/reader/feed" "github.com/miniflux/miniflux/reader/feed"
"github.com/miniflux/miniflux/url" "github.com/miniflux/miniflux/url"
@ -87,7 +87,7 @@ func parseDocument(websiteURL string, data io.Reader) (Subscriptions, error) {
} }
if subscription.URL != "" { if subscription.URL != "" {
log.Println("[FindSubscriptions]", subscription) logger.Debug("[FindSubscriptions] %s", subscription)
subscriptions = append(subscriptions, subscription) subscriptions = append(subscriptions, subscription)
} }
}) })

View file

@ -5,9 +5,9 @@
package scheduler package scheduler
import ( import (
"log"
"time" "time"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/storage" "github.com/miniflux/miniflux/storage"
) )
@ -18,9 +18,9 @@ func NewScheduler(store *storage.Storage, workerPool *WorkerPool, frequency, bat
for now := range c { for now := range c {
jobs, err := store.NewBatch(batchSize) jobs, err := store.NewBatch(batchSize)
if err != nil { if err != nil {
log.Println("[Scheduler]", err) logger.Error("[Scheduler] %v", err)
} else { } else {
log.Printf("[Scheduler:%v] => Pushing %d jobs\n", now, len(jobs)) logger.Debug("[Scheduler:%v] => Pushing %d jobs", now, len(jobs))
workerPool.Push(jobs) workerPool.Push(jobs)
} }
} }

View file

@ -5,9 +5,9 @@
package scheduler package scheduler
import ( import (
"log"
"time" "time"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/reader/feed" "github.com/miniflux/miniflux/reader/feed"
) )
@ -20,15 +20,15 @@ type Worker struct {
// Run wait for a job and refresh the given feed. // Run wait for a job and refresh the given feed.
func (w *Worker) Run(c chan model.Job) { func (w *Worker) Run(c chan model.Job) {
log.Printf("[Worker] #%d started\n", w.id) logger.Debug("[Worker] #%d started", w.id)
for { for {
job := <-c job := <-c
log.Printf("[Worker #%d] got userID=%d, feedID=%d\n", w.id, job.UserID, job.FeedID) logger.Debug("[Worker #%d] got userID=%d, feedID=%d", w.id, job.UserID, job.FeedID)
err := w.feedHandler.RefreshFeed(job.UserID, job.FeedID) err := w.feedHandler.RefreshFeed(job.UserID, job.FeedID)
if err != nil { if err != nil {
log.Println("Worker:", err) logger.Error("[Worker] %v", err)
} }
time.Sleep(time.Millisecond * 1000) time.Sleep(time.Millisecond * 1000)

View file

@ -5,9 +5,9 @@
package core package core
import ( import (
"log"
"net/http" "net/http"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/server/middleware" "github.com/miniflux/miniflux/server/middleware"
"github.com/miniflux/miniflux/server/route" "github.com/miniflux/miniflux/server/route"
@ -63,11 +63,11 @@ func (c *Context) LoggedUser() *model.User {
var err error var err error
c.user, err = c.store.UserByID(c.UserID()) c.user, err = c.store.UserByID(c.UserID())
if err != nil { if err != nil {
log.Fatalln(err) logger.Fatal("[Context] %v", err)
} }
if c.user == nil { if c.user == nil {
log.Fatalln("Unable to find user from context") logger.Fatal("Unable to find user from context")
} }
} }
@ -86,7 +86,7 @@ func (c *Context) CsrfToken() string {
return v.(string) return v.(string)
} }
log.Println("No CSRF token in context!") logger.Error("No CSRF token in context!")
return "" return ""
} }

View file

@ -5,12 +5,12 @@
package core package core
import ( import (
"log"
"net/http" "net/http"
"time" "time"
"github.com/miniflux/miniflux/helper" "github.com/miniflux/miniflux/helper"
"github.com/miniflux/miniflux/locale" "github.com/miniflux/miniflux/locale"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/server/middleware" "github.com/miniflux/miniflux/server/middleware"
"github.com/miniflux/miniflux/server/template" "github.com/miniflux/miniflux/server/template"
"github.com/miniflux/miniflux/storage" "github.com/miniflux/miniflux/storage"
@ -34,7 +34,7 @@ type Handler struct {
func (h *Handler) Use(f HandlerFunc) http.Handler { func (h *Handler) Use(f HandlerFunc) http.Handler {
return h.middleware.WrapFunc(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return h.middleware.WrapFunc(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer helper.ExecutionTime(time.Now(), r.URL.Path) defer helper.ExecutionTime(time.Now(), r.URL.Path)
log.Println(r.Method, r.URL.Path) logger.Debug("[HTTP] %s %s", r.Method, r.URL.Path)
ctx := NewContext(w, r, h.store, h.router) ctx := NewContext(w, r, h.store, h.router)
request := NewRequest(w, r) request := NewRequest(w, r)

View file

@ -5,9 +5,9 @@
package core package core
import ( import (
"log"
"net/http" "net/http"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/server/template" "github.com/miniflux/miniflux/server/template"
) )
@ -30,7 +30,7 @@ func (h *HTMLResponse) ServerError(err error) {
h.writer.Header().Set("Content-Type", "text/html; charset=utf-8") h.writer.Header().Set("Content-Type", "text/html; charset=utf-8")
if err != nil { if err != nil {
log.Println(err) logger.Error("[Internal Server Error] %v", err)
h.writer.Write([]byte("Internal Server Error: " + err.Error())) h.writer.Write([]byte("Internal Server Error: " + err.Error()))
} else { } else {
h.writer.Write([]byte("Internal Server Error")) h.writer.Write([]byte("Internal Server Error"))
@ -43,7 +43,7 @@ func (h *HTMLResponse) BadRequest(err error) {
h.writer.Header().Set("Content-Type", "text/html; charset=utf-8") h.writer.Header().Set("Content-Type", "text/html; charset=utf-8")
if err != nil { if err != nil {
log.Println(err) logger.Error("[Bad Request] %v", err)
h.writer.Write([]byte("Bad Request: " + err.Error())) h.writer.Write([]byte("Bad Request: " + err.Error()))
} else { } else {
h.writer.Write([]byte("Bad Request")) h.writer.Write([]byte("Bad Request"))

View file

@ -7,8 +7,9 @@ package core
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"log"
"net/http" "net/http"
"github.com/miniflux/miniflux/logger"
) )
// JSONResponse handles JSON responses. // JSONResponse handles JSON responses.
@ -39,7 +40,7 @@ func (j *JSONResponse) NoContent() {
// BadRequest sends a JSON response with the status code 400. // BadRequest sends a JSON response with the status code 400.
func (j *JSONResponse) BadRequest(err error) { func (j *JSONResponse) BadRequest(err error) {
log.Println("[API:BadRequest]", err) logger.Error("[Bad Request] %v", err)
j.writer.WriteHeader(http.StatusBadRequest) j.writer.WriteHeader(http.StatusBadRequest)
j.commonHeaders() j.commonHeaders()
@ -50,7 +51,7 @@ func (j *JSONResponse) BadRequest(err error) {
// NotFound sends a JSON response with the status code 404. // NotFound sends a JSON response with the status code 404.
func (j *JSONResponse) NotFound(err error) { func (j *JSONResponse) NotFound(err error) {
log.Println("[API:NotFound]", err) logger.Error("[Not Found] %v", err)
j.writer.WriteHeader(http.StatusNotFound) j.writer.WriteHeader(http.StatusNotFound)
j.commonHeaders() j.commonHeaders()
j.writer.Write(j.encodeError(err)) j.writer.Write(j.encodeError(err))
@ -58,7 +59,7 @@ func (j *JSONResponse) NotFound(err error) {
// ServerError sends a JSON response with the status code 500. // ServerError sends a JSON response with the status code 500.
func (j *JSONResponse) ServerError(err error) { func (j *JSONResponse) ServerError(err error) {
log.Println("[API:ServerError]", err) logger.Error("[Internal Server Error] %v", err)
j.writer.WriteHeader(http.StatusInternalServerError) j.writer.WriteHeader(http.StatusInternalServerError)
j.commonHeaders() j.commonHeaders()
@ -69,7 +70,7 @@ func (j *JSONResponse) ServerError(err error) {
// Forbidden sends a JSON response with the status code 403. // Forbidden sends a JSON response with the status code 403.
func (j *JSONResponse) Forbidden() { func (j *JSONResponse) Forbidden() {
log.Println("[API:Forbidden]") logger.Info("[API:Forbidden]")
j.writer.WriteHeader(http.StatusForbidden) j.writer.WriteHeader(http.StatusForbidden)
j.commonHeaders() j.commonHeaders()
j.writer.Write(j.encodeError(errors.New("Access Forbidden"))) j.writer.Write(j.encodeError(errors.New("Access Forbidden")))
@ -88,7 +89,7 @@ func (j *JSONResponse) encodeError(err error) []byte {
tmp := errorMsg{ErrorMessage: err.Error()} tmp := errorMsg{ErrorMessage: err.Error()}
data, err := json.Marshal(tmp) data, err := json.Marshal(tmp)
if err != nil { if err != nil {
log.Println("encodeError:", err) logger.Error("encoding error: %v", err)
} }
return data return data
@ -97,7 +98,7 @@ func (j *JSONResponse) encodeError(err error) []byte {
func (j *JSONResponse) toJSON(v interface{}) []byte { func (j *JSONResponse) toJSON(v interface{}) []byte {
b, err := json.Marshal(v) b, err := json.Marshal(v)
if err != nil { if err != nil {
log.Println("Unable to convert interface to JSON:", err) logger.Error("encoding error: %v", err)
return []byte("") return []byte("")
} }

View file

@ -7,12 +7,12 @@ package core
import ( import (
"fmt" "fmt"
"io" "io"
"log"
"mime/multipart" "mime/multipart"
"net/http" "net/http"
"strconv" "strconv"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/miniflux/miniflux/logger"
) )
// Request is a thin wrapper around "http.Request". // Request is a thin wrapper around "http.Request".
@ -68,7 +68,7 @@ func (r *Request) IntegerParam(param string) (int64, error) {
vars := mux.Vars(r.request) vars := mux.Vars(r.request)
value, err := strconv.Atoi(vars[param]) value, err := strconv.Atoi(vars[param])
if err != nil { if err != nil {
log.Println(err) logger.Error("[IntegerParam] %v", err)
return 0, fmt.Errorf("%s parameter is not an integer", param) return 0, fmt.Errorf("%s parameter is not an integer", param)
} }

View file

@ -5,12 +5,12 @@
package fever package fever
import ( import (
"log"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/miniflux/miniflux/integration" "github.com/miniflux/miniflux/integration"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/server/core" "github.com/miniflux/miniflux/server/core"
"github.com/miniflux/miniflux/storage" "github.com/miniflux/miniflux/storage"
@ -183,7 +183,7 @@ is_spark equal to 1.
*/ */
func (c *Controller) handleGroups(ctx *core.Context, request *core.Request, response *core.Response) { func (c *Controller) handleGroups(ctx *core.Context, request *core.Request, response *core.Response) {
userID := ctx.UserID() userID := ctx.UserID()
log.Printf("[Fever] Fetching groups for userID=%d\n", userID) logger.Debug("[Fever] Fetching groups for userID=%d", userID)
categories, err := c.store.Categories(userID) categories, err := c.store.Categories(userID)
if err != nil { if err != nil {
@ -233,7 +233,7 @@ For the “Sparks” super group the items should be limited to feeds with an is
*/ */
func (c *Controller) handleFeeds(ctx *core.Context, request *core.Request, response *core.Response) { func (c *Controller) handleFeeds(ctx *core.Context, request *core.Request, response *core.Response) {
userID := ctx.UserID() userID := ctx.UserID()
log.Printf("[Fever] Fetching feeds for userID=%d\n", userID) logger.Debug("[Fever] Fetching feeds for userID=%d", userID)
feeds, err := c.store.Feeds(userID) feeds, err := c.store.Feeds(userID)
if err != nil { if err != nil {
@ -280,7 +280,7 @@ A PHP/HTML example:
*/ */
func (c *Controller) handleFavicons(ctx *core.Context, request *core.Request, response *core.Response) { func (c *Controller) handleFavicons(ctx *core.Context, request *core.Request, response *core.Response) {
userID := ctx.UserID() userID := ctx.UserID()
log.Printf("[Fever] Fetching favicons for userID=%d\n", userID) logger.Debug("[Fever] Fetching favicons for userID=%d", userID)
icons, err := c.store.Icons(userID) icons, err := c.store.Icons(userID)
if err != nil { if err != nil {
@ -336,7 +336,7 @@ func (c *Controller) handleItems(ctx *core.Context, request *core.Request, respo
userID := ctx.UserID() userID := ctx.UserID()
timezone := ctx.UserTimezone() timezone := ctx.UserTimezone()
log.Printf("[Fever] Fetching items for userID=%d\n", userID) logger.Debug("[Fever] Fetching items for userID=%d", userID)
builder := c.store.GetEntryQueryBuilder(userID, timezone) builder := c.store.GetEntryQueryBuilder(userID, timezone)
builder.WithoutStatus(model.EntryStatusRemoved) builder.WithoutStatus(model.EntryStatusRemoved)
@ -413,7 +413,7 @@ A request with the unread_item_ids argument will return one additional member:
*/ */
func (c *Controller) handleUnreadItems(ctx *core.Context, request *core.Request, response *core.Response) { func (c *Controller) handleUnreadItems(ctx *core.Context, request *core.Request, response *core.Response) {
userID := ctx.UserID() userID := ctx.UserID()
log.Printf("[Fever] Fetching unread items for userID=%d\n", userID) logger.Debug("[Fever] Fetching unread items for userID=%d", userID)
builder := c.store.GetEntryQueryBuilder(userID, ctx.UserTimezone()) builder := c.store.GetEntryQueryBuilder(userID, ctx.UserTimezone())
builder.WithStatus(model.EntryStatusUnread) builder.WithStatus(model.EntryStatusUnread)
@ -444,7 +444,7 @@ with the remote Fever installation.
*/ */
func (c *Controller) handleSavedItems(ctx *core.Context, request *core.Request, response *core.Response) { func (c *Controller) handleSavedItems(ctx *core.Context, request *core.Request, response *core.Response) {
userID := ctx.UserID() userID := ctx.UserID()
log.Printf("[Fever] Fetching saved items for userID=%d\n", userID) logger.Debug("[Fever] Fetching saved items for userID=%d", userID)
var result savedResponse var result savedResponse
result.SetCommonValues() result.SetCommonValues()
@ -471,7 +471,7 @@ A link object has the following members:
*/ */
func (c *Controller) handleLinks(ctx *core.Context, request *core.Request, response *core.Response) { func (c *Controller) handleLinks(ctx *core.Context, request *core.Request, response *core.Response) {
userID := ctx.UserID() userID := ctx.UserID()
log.Printf("[Fever] Fetching links for userID=%d\n", userID) logger.Debug("[Fever] Fetching links for userID=%d", userID)
var result linksResponse var result linksResponse
result.SetCommonValues() result.SetCommonValues()
@ -485,7 +485,7 @@ func (c *Controller) handleLinks(ctx *core.Context, request *core.Request, respo
*/ */
func (c *Controller) handleWriteItems(ctx *core.Context, request *core.Request, response *core.Response) { func (c *Controller) handleWriteItems(ctx *core.Context, request *core.Request, response *core.Response) {
userID := ctx.UserID() userID := ctx.UserID()
log.Printf("[Fever] Receiving mark=item call for userID=%d\n", userID) logger.Debug("[Fever] Receiving mark=item call for userID=%d", userID)
entryID := request.FormIntegerValue("id") entryID := request.FormIntegerValue("id")
if entryID <= 0 { if entryID <= 0 {
@ -534,7 +534,7 @@ func (c *Controller) handleWriteItems(ctx *core.Context, request *core.Request,
*/ */
func (c *Controller) handleWriteFeeds(ctx *core.Context, request *core.Request, response *core.Response) { func (c *Controller) handleWriteFeeds(ctx *core.Context, request *core.Request, response *core.Response) {
userID := ctx.UserID() userID := ctx.UserID()
log.Printf("[Fever] Receiving mark=feed call for userID=%d\n", userID) logger.Debug("[Fever] Receiving mark=feed call for userID=%d", userID)
feedID := request.FormIntegerValue("id") feedID := request.FormIntegerValue("id")
if feedID <= 0 { if feedID <= 0 {
@ -574,7 +574,7 @@ func (c *Controller) handleWriteFeeds(ctx *core.Context, request *core.Request,
*/ */
func (c *Controller) handleWriteGroups(ctx *core.Context, request *core.Request, response *core.Response) { func (c *Controller) handleWriteGroups(ctx *core.Context, request *core.Request, response *core.Response) {
userID := ctx.UserID() userID := ctx.UserID()
log.Printf("[Fever] Receiving mark=group call for userID=%d\n", userID) logger.Debug("[Fever] Receiving mark=group call for userID=%d", userID)
groupID := request.FormIntegerValue("id") groupID := request.FormIntegerValue("id")
if groupID < 0 { if groupID < 0 {

View file

@ -6,9 +6,9 @@ package middleware
import ( import (
"context" "context"
"log"
"net/http" "net/http"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/storage" "github.com/miniflux/miniflux/storage"
) )
@ -25,14 +25,14 @@ func (b *BasicAuthMiddleware) Handler(next http.Handler) http.Handler {
username, password, authOK := r.BasicAuth() username, password, authOK := r.BasicAuth()
if !authOK { if !authOK {
log.Println("[Middleware:BasicAuth] No authentication headers sent") logger.Debug("[Middleware:BasicAuth] No authentication headers sent")
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(errorResponse)) w.Write([]byte(errorResponse))
return return
} }
if err := b.store.CheckPassword(username, password); err != nil { if err := b.store.CheckPassword(username, password); err != nil {
log.Println("[Middleware:BasicAuth] Invalid username or password:", username) logger.Info("[Middleware:BasicAuth] Invalid username or password: %s", username)
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(errorResponse)) w.Write([]byte(errorResponse))
return return
@ -40,13 +40,13 @@ func (b *BasicAuthMiddleware) Handler(next http.Handler) http.Handler {
user, err := b.store.UserByUsername(username) user, err := b.store.UserByUsername(username)
if err != nil || user == nil { if err != nil || user == nil {
log.Println("[Middleware:BasicAuth] User not found:", username) logger.Info("[Middleware:BasicAuth] User not found: %s", username)
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(errorResponse)) w.Write([]byte(errorResponse))
return return
} }
log.Println("[Middleware:BasicAuth] User authenticated:", username) logger.Info("[Middleware:BasicAuth] User authenticated: %s", username)
b.store.SetLastLogin(user.ID) b.store.SetLastLogin(user.ID)
ctx := r.Context() ctx := r.Context()

View file

@ -6,9 +6,9 @@ package middleware
import ( import (
"context" "context"
"log"
"net/http" "net/http"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/storage" "github.com/miniflux/miniflux/storage"
) )
@ -20,25 +20,25 @@ type FeverMiddleware struct {
// Handler executes the middleware. // Handler executes the middleware.
func (f *FeverMiddleware) Handler(next http.Handler) http.Handler { func (f *FeverMiddleware) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("[Middleware:Fever]") logger.Debug("[Middleware:Fever]")
apiKey := r.FormValue("api_key") apiKey := r.FormValue("api_key")
user, err := f.store.UserByFeverToken(apiKey) user, err := f.store.UserByFeverToken(apiKey)
if err != nil { if err != nil {
log.Println(err) logger.Error("[Fever] %v", err)
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"api_version": 3, "auth": 0}`)) w.Write([]byte(`{"api_version": 3, "auth": 0}`))
return return
} }
if user == nil { if user == nil {
log.Println("[Middleware:Fever] Fever authentication failure") logger.Info("[Middleware:Fever] Fever authentication failure")
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"api_version": 3, "auth": 0}`)) w.Write([]byte(`{"api_version": 3, "auth": 0}`))
return return
} }
log.Printf("[Middleware:Fever] User #%d is authenticated\n", user.ID) logger.Info("[Middleware:Fever] User #%d is authenticated", user.ID)
f.store.SetLastLogin(user.ID) f.store.SetLastLogin(user.ID)
ctx := r.Context() ctx := r.Context()

View file

@ -6,9 +6,9 @@ package middleware
import ( import (
"context" "context"
"log"
"net/http" "net/http"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/server/route" "github.com/miniflux/miniflux/server/route"
"github.com/miniflux/miniflux/storage" "github.com/miniflux/miniflux/storage"
@ -28,14 +28,14 @@ func (s *SessionMiddleware) Handler(next http.Handler) http.Handler {
session := s.getSessionFromCookie(r) session := s.getSessionFromCookie(r)
if session == nil { if session == nil {
log.Println("[Middleware:Session] Session not found") logger.Debug("[Middleware:Session] Session not found")
if s.isPublicRoute(r) { if s.isPublicRoute(r) {
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
} else { } else {
http.Redirect(w, r, route.Path(s.router, "login"), http.StatusFound) http.Redirect(w, r, route.Path(s.router, "login"), http.StatusFound)
} }
} else { } else {
log.Println("[Middleware:Session]", session) logger.Debug("[Middleware:Session] %s", session)
ctx := r.Context() ctx := r.Context()
ctx = context.WithValue(ctx, UserIDContextKey, session.UserID) ctx = context.WithValue(ctx, UserIDContextKey, session.UserID)
ctx = context.WithValue(ctx, IsAuthenticatedContextKey, true) ctx = context.WithValue(ctx, IsAuthenticatedContextKey, true)
@ -63,7 +63,7 @@ func (s *SessionMiddleware) getSessionFromCookie(r *http.Request) *model.Session
session, err := s.store.SessionByToken(sessionCookie.Value) session, err := s.store.SessionByToken(sessionCookie.Value)
if err != nil { if err != nil {
log.Println(err) logger.Error("[SessionMiddleware] %v", err)
return nil return nil
} }

View file

@ -6,9 +6,9 @@ package middleware
import ( import (
"context" "context"
"log"
"net/http" "net/http"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/storage" "github.com/miniflux/miniflux/storage"
) )
@ -25,10 +25,10 @@ func (t *TokenMiddleware) Handler(next http.Handler) http.Handler {
token := t.getTokenValueFromCookie(r) token := t.getTokenValueFromCookie(r)
if token == nil { if token == nil {
log.Println("[Middleware:Token] Token not found") logger.Debug("[Middleware:Token] Token not found")
token, err = t.store.CreateToken() token, err = t.store.CreateToken()
if err != nil { if err != nil {
log.Println(err) logger.Error("[Middleware:Token] %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return return
} }
@ -43,13 +43,13 @@ func (t *TokenMiddleware) Handler(next http.Handler) http.Handler {
http.SetCookie(w, cookie) http.SetCookie(w, cookie)
} else { } else {
log.Println("[Middleware:Token]", token) logger.Info("[Middleware:Token] %s", token)
} }
isTokenValid := token.Value == r.FormValue("csrf") || token.Value == r.Header.Get("X-Csrf-Token") isTokenValid := token.Value == r.FormValue("csrf") || token.Value == r.Header.Get("X-Csrf-Token")
if r.Method == "POST" && !isTokenValid { if r.Method == "POST" && !isTokenValid {
log.Println("[Middleware:CSRF] Invalid or missing CSRF token!") logger.Error("[Middleware:CSRF] Invalid or missing CSRF token!")
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Invalid or missing CSRF token!")) w.Write([]byte("Invalid or missing CSRF token!"))
} else { } else {
@ -68,7 +68,7 @@ func (t *TokenMiddleware) getTokenValueFromCookie(r *http.Request) *model.Token
token, err := t.store.Token(tokenCookie.Value) token, err := t.store.Token(tokenCookie.Value)
if err != nil { if err != nil {
log.Println(err) logger.Error("[Middleware:Token] %v", err)
return nil return nil
} }

View file

@ -5,17 +5,17 @@
package route package route
import ( import (
"log"
"strconv" "strconv"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/miniflux/miniflux/logger"
) )
// Path returns the defined route based on given arguments. // Path returns the defined route based on given arguments.
func Path(router *mux.Router, name string, args ...interface{}) string { func Path(router *mux.Router, name string, args ...interface{}) string {
route := router.Get(name) route := router.Get(name)
if route == nil { if route == nil {
log.Fatalln("Route not found:", name) logger.Fatal("[Route] Route not found: %s", name)
} }
var pairs []string var pairs []string
@ -31,7 +31,7 @@ func Path(router *mux.Router, name string, args ...interface{}) string {
result, err := route.URLPath(pairs...) result, err := route.URLPath(pairs...)
if err != nil { if err != nil {
log.Fatalln(err) logger.Fatal("[Route] %v", err)
} }
return result.String() return result.String()

View file

@ -6,11 +6,11 @@ package server
import ( import (
"crypto/tls" "crypto/tls"
"log"
"net/http" "net/http"
"time" "time"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/scheduler" "github.com/miniflux/miniflux/scheduler"
"golang.org/x/crypto/acme/autocert" "golang.org/x/crypto/acme/autocert"
@ -46,20 +46,20 @@ func startServer(cfg *config.Config, handler *mux.Router) *http.Server {
} }
go func() { go func() {
log.Printf(`Listening on "%s" by using auto-configured certificate for "%s"`, server.Addr, certDomain) logger.Info(`Listening on "%s" by using auto-configured certificate for "%s"`, server.Addr, certDomain)
log.Fatalln(server.Serve(certManager.Listener())) logger.Fatal(server.Serve(certManager.Listener()).Error())
}() }()
} else if certFile != "" && keyFile != "" { } else if certFile != "" && keyFile != "" {
server.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} server.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
go func() { go func() {
log.Printf(`Listening on "%s" by using certificate "%s" and key "%s"`, server.Addr, certFile, keyFile) logger.Info(`Listening on "%s" by using certificate "%s" and key "%s"`, server.Addr, certFile, keyFile)
log.Fatalln(server.ListenAndServeTLS(certFile, keyFile)) logger.Fatal(server.ListenAndServeTLS(certFile, keyFile).Error())
}() }()
} else { } else {
go func() { go func() {
log.Printf(`Listening on "%s" without TLS`, server.Addr) logger.Info(`Listening on "%s" without TLS`, server.Addr)
log.Fatalln(server.ListenAndServe()) logger.Fatal(server.ListenAndServe().Error())
}() }()
} }

View file

@ -1,5 +1,5 @@
// Code generated by go generate; DO NOT EDIT. // Code generated by go generate; DO NOT EDIT.
// 2017-12-12 21:44:02.652999925 -0800 PST m=+0.007410628 // 2017-12-15 18:49:24.03816003 -0800 PST m=+0.010755902
package static package static

View file

@ -1,5 +1,5 @@
// Code generated by go generate; DO NOT EDIT. // Code generated by go generate; DO NOT EDIT.
// 2017-12-13 20:40:03.300001544 -0800 PST m=+0.017854402 // 2017-12-15 18:49:24.040014054 -0800 PST m=+0.012609926
package static package static

View file

@ -1,5 +1,5 @@
// Code generated by go generate; DO NOT EDIT. // Code generated by go generate; DO NOT EDIT.
// 2017-12-12 21:44:02.656535482 -0800 PST m=+0.010946185 // 2017-12-15 18:49:24.041876548 -0800 PST m=+0.014472420
package static package static

View file

@ -1,5 +1,5 @@
// Code generated by go generate; DO NOT EDIT. // Code generated by go generate; DO NOT EDIT.
// 2017-12-12 21:44:02.670455816 -0800 PST m=+0.024866519 // 2017-12-15 18:49:24.05332735 -0800 PST m=+0.025923222
package template package template

View file

@ -8,7 +8,6 @@ import (
"bytes" "bytes"
"html/template" "html/template"
"io" "io"
"log"
"net/mail" "net/mail"
"strings" "strings"
"time" "time"
@ -16,6 +15,7 @@ import (
"github.com/miniflux/miniflux/config" "github.com/miniflux/miniflux/config"
"github.com/miniflux/miniflux/errors" "github.com/miniflux/miniflux/errors"
"github.com/miniflux/miniflux/locale" "github.com/miniflux/miniflux/locale"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/server/route" "github.com/miniflux/miniflux/server/route"
"github.com/miniflux/miniflux/server/template/helper" "github.com/miniflux/miniflux/server/template/helper"
"github.com/miniflux/miniflux/server/ui/filter" "github.com/miniflux/miniflux/server/ui/filter"
@ -42,7 +42,6 @@ func (e *Engine) parseAll() {
return e.cfg.Get("OAUTH2_PROVIDER", "") == provider return e.cfg.Get("OAUTH2_PROVIDER", "") == provider
}, },
"hasKey": func(dict map[string]string, key string) bool { "hasKey": func(dict map[string]string, key string) bool {
log.Println(dict)
if value, found := dict[key]; found { if value, found := dict[key]; found {
return value != "" return value != ""
} }
@ -110,7 +109,7 @@ func (e *Engine) parseAll() {
} }
for name, content := range templateViewsMap { for name, content := range templateViewsMap {
log.Println("Parsing template:", name) logger.Debug("[Template] Parsing: %s", name)
e.templates[name] = template.Must(template.New("main").Funcs(funcMap).Parse(commonTemplates + content)) e.templates[name] = template.Must(template.New("main").Funcs(funcMap).Parse(commonTemplates + content))
} }
} }
@ -124,13 +123,13 @@ func (e *Engine) SetLanguage(language string) {
func (e *Engine) Execute(w io.Writer, name string, data interface{}) { func (e *Engine) Execute(w io.Writer, name string, data interface{}) {
tpl, ok := e.templates[name] tpl, ok := e.templates[name]
if !ok { if !ok {
log.Fatalf("The template %s does not exists.\n", name) logger.Fatal("[Template] The template %s does not exists", name)
} }
var b bytes.Buffer var b bytes.Buffer
err := tpl.ExecuteTemplate(&b, "base", data) err := tpl.ExecuteTemplate(&b, "base", data)
if err != nil { if err != nil {
log.Fatalf("Unable to render template: %v\n", err) logger.Fatal("[Template] Unable to render template: %v", err)
} }
b.WriteTo(w) b.WriteTo(w)

View file

@ -1,5 +1,5 @@
// Code generated by go generate; DO NOT EDIT. // Code generated by go generate; DO NOT EDIT.
// 2017-12-12 21:44:02.658745181 -0800 PST m=+0.013155884 // 2017-12-15 18:49:24.044316922 -0800 PST m=+0.016912794
package template package template

View file

@ -6,8 +6,8 @@ package controller
import ( import (
"errors" "errors"
"log"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/server/core" "github.com/miniflux/miniflux/server/core"
"github.com/miniflux/miniflux/server/ui/form" "github.com/miniflux/miniflux/server/ui/form"
@ -126,7 +126,7 @@ func (c *Controller) SaveCategory(ctx *core.Context, request *core.Request, resp
category := model.Category{Title: categoryForm.Title, UserID: user.ID} category := model.Category{Title: categoryForm.Title, UserID: user.ID}
err = c.store.CreateCategory(&category) err = c.store.CreateCategory(&category)
if err != nil { if err != nil {
log.Println(err) logger.Info("[Controller:CreateCategory] %v", err)
response.HTML().Render("create_category", args.Merge(tplParams{ response.HTML().Render("create_category", args.Merge(tplParams{
"errorMessage": "Unable to create this category.", "errorMessage": "Unable to create this category.",
})) }))
@ -142,7 +142,7 @@ func (c *Controller) EditCategory(ctx *core.Context, request *core.Request, resp
category, err := c.getCategoryFromURL(ctx, request, response) category, err := c.getCategoryFromURL(ctx, request, response)
if err != nil { if err != nil {
log.Println(err) logger.Error("[Controller:EditCategory] %v", err)
return return
} }
@ -161,7 +161,7 @@ func (c *Controller) UpdateCategory(ctx *core.Context, request *core.Request, re
category, err := c.getCategoryFromURL(ctx, request, response) category, err := c.getCategoryFromURL(ctx, request, response)
if err != nil { if err != nil {
log.Println(err) logger.Error("[Controller:UpdateCategory] %v", err)
return return
} }
@ -188,7 +188,7 @@ func (c *Controller) UpdateCategory(ctx *core.Context, request *core.Request, re
err = c.store.UpdateCategory(categoryForm.Merge(category)) err = c.store.UpdateCategory(categoryForm.Merge(category))
if err != nil { if err != nil {
log.Println(err) logger.Error("[Controller:UpdateCategory] %v", err)
response.HTML().Render("edit_category", args.Merge(tplParams{ response.HTML().Render("edit_category", args.Merge(tplParams{
"errorMessage": "Unable to update this category.", "errorMessage": "Unable to update this category.",
})) }))

View file

@ -6,8 +6,8 @@ package controller
import ( import (
"errors" "errors"
"log"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/reader/sanitizer" "github.com/miniflux/miniflux/reader/sanitizer"
"github.com/miniflux/miniflux/integration" "github.com/miniflux/miniflux/integration"
@ -126,7 +126,7 @@ func (c *Controller) ShowFeedEntry(ctx *core.Context, request *core.Request, res
if entry.Status == model.EntryStatusUnread { if entry.Status == model.EntryStatusUnread {
err = c.store.SetEntriesStatus(user.ID, []int64{entry.ID}, model.EntryStatusRead) err = c.store.SetEntriesStatus(user.ID, []int64{entry.ID}, model.EntryStatusRead)
if err != nil { if err != nil {
log.Println(err) logger.Error("[Controller:ShowFeedEntry] %v", err)
response.HTML().ServerError(nil) response.HTML().ServerError(nil)
return return
} }
@ -202,7 +202,7 @@ func (c *Controller) ShowCategoryEntry(ctx *core.Context, request *core.Request,
if entry.Status == model.EntryStatusUnread { if entry.Status == model.EntryStatusUnread {
err = c.store.SetEntriesStatus(user.ID, []int64{entry.ID}, model.EntryStatusRead) err = c.store.SetEntriesStatus(user.ID, []int64{entry.ID}, model.EntryStatusRead)
if err != nil { if err != nil {
log.Println(err) logger.Error("[Controller:ShowCategoryEntry] %v", err)
response.HTML().ServerError(nil) response.HTML().ServerError(nil)
return return
} }
@ -297,7 +297,7 @@ func (c *Controller) ShowUnreadEntry(ctx *core.Context, request *core.Request, r
if entry.Status == model.EntryStatusUnread { if entry.Status == model.EntryStatusUnread {
err = c.store.SetEntriesStatus(user.ID, []int64{entry.ID}, model.EntryStatusRead) err = c.store.SetEntriesStatus(user.ID, []int64{entry.ID}, model.EntryStatusRead)
if err != nil { if err != nil {
log.Println(err) logger.Error("[Controller:ShowUnreadEntry] %v", err)
response.HTML().ServerError(nil) response.HTML().ServerError(nil)
return return
} }
@ -379,7 +379,7 @@ func (c *Controller) UpdateEntriesStatus(ctx *core.Context, request *core.Reques
entryIDs, status, err := payload.DecodeEntryStatusPayload(request.Body()) entryIDs, status, err := payload.DecodeEntryStatusPayload(request.Body())
if err != nil { if err != nil {
log.Println(err) logger.Error("[Controller:UpdateEntryStatus] %v", err)
response.JSON().BadRequest(nil) response.JSON().BadRequest(nil)
return return
} }
@ -391,7 +391,7 @@ func (c *Controller) UpdateEntriesStatus(ctx *core.Context, request *core.Reques
err = c.store.SetEntriesStatus(user.ID, entryIDs, status) err = c.store.SetEntriesStatus(user.ID, entryIDs, status)
if err != nil { if err != nil {
log.Println(err) logger.Error("[Controller:UpdateEntryStatus] %v", err)
response.JSON().ServerError(nil) response.JSON().ServerError(nil)
return return
} }

View file

@ -6,8 +6,8 @@ package controller
import ( import (
"errors" "errors"
"log"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/server/core" "github.com/miniflux/miniflux/server/core"
"github.com/miniflux/miniflux/server/ui/form" "github.com/miniflux/miniflux/server/ui/form"
@ -140,7 +140,7 @@ func (c *Controller) UpdateFeed(ctx *core.Context, request *core.Request, respon
err = c.store.UpdateFeed(feedForm.Merge(feed)) err = c.store.UpdateFeed(feedForm.Merge(feed))
if err != nil { if err != nil {
log.Println(err) logger.Error("[Controller:EditFeed] %v", err)
response.HTML().Render("edit_feed", args.Merge(tplParams{ response.HTML().Render("edit_feed", args.Merge(tplParams{
"errorMessage": "Unable to update this feed.", "errorMessage": "Unable to update this feed.",
})) }))
@ -177,7 +177,7 @@ func (c *Controller) RefreshFeed(ctx *core.Context, request *core.Request, respo
user := ctx.LoggedUser() user := ctx.LoggedUser()
if err := c.feedHandler.RefreshFeed(user.ID, feedID); err != nil { if err := c.feedHandler.RefreshFeed(user.ID, feedID); err != nil {
log.Println("[UI:RefreshFeed]", err) logger.Error("[Controller:RefreshFeed] %v", err)
} }
response.Redirect(ctx.Route("feedEntries", "feedID", feedID)) response.Redirect(ctx.Route("feedEntries", "feedID", feedID))

View file

@ -5,10 +5,10 @@
package controller package controller
import ( import (
"log"
"net/http" "net/http"
"time" "time"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/server/core" "github.com/miniflux/miniflux/server/core"
"github.com/miniflux/miniflux/server/ui/form" "github.com/miniflux/miniflux/server/ui/form"
@ -36,13 +36,13 @@ func (c *Controller) CheckLogin(ctx *core.Context, request *core.Request, respon
} }
if err := authForm.Validate(); err != nil { if err := authForm.Validate(); err != nil {
log.Println(err) logger.Error("[Controller:CheckLogin] %v", err)
response.HTML().Render("login", tplParams) response.HTML().Render("login", tplParams)
return return
} }
if err := c.store.CheckPassword(authForm.Username, authForm.Password); err != nil { if err := c.store.CheckPassword(authForm.Username, authForm.Password); err != nil {
log.Println(err) logger.Error("[Controller:CheckLogin] %v", err)
response.HTML().Render("login", tplParams) response.HTML().Render("login", tplParams)
return return
} }
@ -58,7 +58,7 @@ func (c *Controller) CheckLogin(ctx *core.Context, request *core.Request, respon
return return
} }
log.Printf("[UI:CheckLogin] username=%s just logged in\n", authForm.Username) logger.Info("[Controller:CheckLogin] username=%s just logged in", authForm.Username)
cookie := &http.Cookie{ cookie := &http.Cookie{
Name: "sessionID", Name: "sessionID",
@ -78,7 +78,7 @@ func (c *Controller) Logout(ctx *core.Context, request *core.Request, response *
sessionCookie := request.Cookie("sessionID") sessionCookie := request.Cookie("sessionID")
if err := c.store.RemoveSessionByToken(user.ID, sessionCookie); err != nil { if err := c.store.RemoveSessionByToken(user.ID, sessionCookie); err != nil {
log.Printf("[UI:Logout] %v", err) logger.Error("[Controller:Logout] %v", err)
} }
cookie := &http.Cookie{ cookie := &http.Cookie{

View file

@ -5,10 +5,10 @@
package controller package controller
import ( import (
"log"
"net/http" "net/http"
"github.com/miniflux/miniflux/config" "github.com/miniflux/miniflux/config"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/server/core" "github.com/miniflux/miniflux/server/core"
"github.com/miniflux/miniflux/server/oauth2" "github.com/miniflux/miniflux/server/oauth2"
@ -19,14 +19,14 @@ import (
func (c *Controller) OAuth2Redirect(ctx *core.Context, request *core.Request, response *core.Response) { func (c *Controller) OAuth2Redirect(ctx *core.Context, request *core.Request, response *core.Response) {
provider := request.StringParam("provider", "") provider := request.StringParam("provider", "")
if provider == "" { if provider == "" {
log.Println("[OAuth2] Invalid or missing provider") logger.Error("[OAuth2] Invalid or missing provider")
response.Redirect(ctx.Route("login")) response.Redirect(ctx.Route("login"))
return return
} }
authProvider, err := getOAuth2Manager(c.cfg).Provider(provider) authProvider, err := getOAuth2Manager(c.cfg).Provider(provider)
if err != nil { if err != nil {
log.Println("[OAuth2]", err) logger.Error("[OAuth2] %v", err)
response.Redirect(ctx.Route("login")) response.Redirect(ctx.Route("login"))
return return
} }
@ -38,35 +38,35 @@ func (c *Controller) OAuth2Redirect(ctx *core.Context, request *core.Request, re
func (c *Controller) OAuth2Callback(ctx *core.Context, request *core.Request, response *core.Response) { func (c *Controller) OAuth2Callback(ctx *core.Context, request *core.Request, response *core.Response) {
provider := request.StringParam("provider", "") provider := request.StringParam("provider", "")
if provider == "" { if provider == "" {
log.Println("[OAuth2] Invalid or missing provider") logger.Error("[OAuth2] Invalid or missing provider")
response.Redirect(ctx.Route("login")) response.Redirect(ctx.Route("login"))
return return
} }
code := request.QueryStringParam("code", "") code := request.QueryStringParam("code", "")
if code == "" { if code == "" {
log.Println("[OAuth2] No code received on callback") logger.Error("[OAuth2] No code received on callback")
response.Redirect(ctx.Route("login")) response.Redirect(ctx.Route("login"))
return return
} }
state := request.QueryStringParam("state", "") state := request.QueryStringParam("state", "")
if state != ctx.CsrfToken() { if state != ctx.CsrfToken() {
log.Println("[OAuth2] Invalid state value") logger.Error("[OAuth2] Invalid state value")
response.Redirect(ctx.Route("login")) response.Redirect(ctx.Route("login"))
return return
} }
authProvider, err := getOAuth2Manager(c.cfg).Provider(provider) authProvider, err := getOAuth2Manager(c.cfg).Provider(provider)
if err != nil { if err != nil {
log.Println("[OAuth2]", err) logger.Error("[OAuth2] %v", err)
response.Redirect(ctx.Route("login")) response.Redirect(ctx.Route("login"))
return return
} }
profile, err := authProvider.GetProfile(code) profile, err := authProvider.GetProfile(code)
if err != nil { if err != nil {
log.Println("[OAuth2]", err) logger.Error("[OAuth2] %v", err)
response.Redirect(ctx.Route("login")) response.Redirect(ctx.Route("login"))
return return
} }
@ -116,7 +116,7 @@ func (c *Controller) OAuth2Callback(ctx *core.Context, request *core.Request, re
return return
} }
log.Printf("[UI:OAuth2Callback] username=%s just logged in\n", user.Username) logger.Info("[Controller:OAuth2Callback] username=%s just logged in", user.Username)
cookie := &http.Cookie{ cookie := &http.Cookie{
Name: "sessionID", Name: "sessionID",
@ -134,14 +134,14 @@ func (c *Controller) OAuth2Callback(ctx *core.Context, request *core.Request, re
func (c *Controller) OAuth2Unlink(ctx *core.Context, request *core.Request, response *core.Response) { func (c *Controller) OAuth2Unlink(ctx *core.Context, request *core.Request, response *core.Response) {
provider := request.StringParam("provider", "") provider := request.StringParam("provider", "")
if provider == "" { if provider == "" {
log.Println("[OAuth2] Invalid or missing provider") logger.Info("[OAuth2] Invalid or missing provider")
response.Redirect(ctx.Route("login")) response.Redirect(ctx.Route("login"))
return return
} }
authProvider, err := getOAuth2Manager(c.cfg).Provider(provider) authProvider, err := getOAuth2Manager(c.cfg).Provider(provider)
if err != nil { if err != nil {
log.Println("[OAuth2]", err) logger.Error("[OAuth2] %v", err)
response.Redirect(ctx.Route("settings")) response.Redirect(ctx.Route("settings"))
return return
} }

View file

@ -5,8 +5,7 @@
package controller package controller
import ( import (
"log" "github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/server/core" "github.com/miniflux/miniflux/server/core"
) )
@ -39,14 +38,19 @@ func (c *Controller) Import(ctx *core.Context, request *core.Request, response *
func (c *Controller) UploadOPML(ctx *core.Context, request *core.Request, response *core.Response) { func (c *Controller) UploadOPML(ctx *core.Context, request *core.Request, response *core.Response) {
file, fileHeader, err := request.File("file") file, fileHeader, err := request.File("file")
if err != nil { if err != nil {
log.Println(err) logger.Error("[Controller:UploadOPML] %v", err)
response.Redirect(ctx.Route("import")) response.Redirect(ctx.Route("import"))
return return
} }
defer file.Close() defer file.Close()
user := ctx.LoggedUser() user := ctx.LoggedUser()
log.Printf("[UI:UploadOPML] User #%d uploaded this file: %s (%d bytes)\n", user.ID, fileHeader.Filename, fileHeader.Size) logger.Info(
"[Controller:UploadOPML] User #%d uploaded this file: %s (%d bytes)",
user.ID,
fileHeader.Filename,
fileHeader.Size,
)
if impErr := c.opmlHandler.Import(user.ID, file); impErr != nil { if impErr := c.opmlHandler.Import(user.ID, file); impErr != nil {
args, err := c.getCommonTemplateArgs(ctx) args, err := c.getCommonTemplateArgs(ctx)

View file

@ -8,11 +8,11 @@ import (
"encoding/base64" "encoding/base64"
"errors" "errors"
"io/ioutil" "io/ioutil"
"log"
"time" "time"
"github.com/miniflux/miniflux/helper" "github.com/miniflux/miniflux/helper"
"github.com/miniflux/miniflux/http" "github.com/miniflux/miniflux/http"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/server/core" "github.com/miniflux/miniflux/server/core"
) )
@ -39,7 +39,7 @@ func (c *Controller) ImageProxy(ctx *core.Context, request *core.Request, respon
client := http.NewClient(string(decodedURL)) client := http.NewClient(string(decodedURL))
resp, err := client.Get() resp, err := client.Get()
if err != nil { if err != nil {
log.Println("[ImageProxy]", err) logger.Error("[Controller:ImageProxy] %v", err)
response.HTML().NotFound() response.HTML().NotFound()
return return
} }

View file

@ -5,8 +5,7 @@
package controller package controller
import ( import (
"log" "github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/server/core" "github.com/miniflux/miniflux/server/core"
) )
@ -45,7 +44,7 @@ func (c *Controller) RemoveSession(ctx *core.Context, request *core.Request, res
err = c.store.RemoveSessionByID(user.ID, sessionID) err = c.store.RemoveSessionByID(user.ID, sessionID)
if err != nil { if err != nil {
log.Println("[UI:RemoveSession]", err) logger.Error("[Controller:RemoveSession] %v", err)
} }
response.Redirect(ctx.Route("sessions")) response.Redirect(ctx.Route("sessions"))

View file

@ -5,9 +5,8 @@
package controller package controller
import ( import (
"log"
"github.com/miniflux/miniflux/locale" "github.com/miniflux/miniflux/locale"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/server/core" "github.com/miniflux/miniflux/server/core"
"github.com/miniflux/miniflux/server/ui/form" "github.com/miniflux/miniflux/server/ui/form"
@ -55,7 +54,7 @@ func (c *Controller) UpdateSettings(ctx *core.Context, request *core.Request, re
err = c.store.UpdateUser(settingsForm.Merge(user)) err = c.store.UpdateUser(settingsForm.Merge(user))
if err != nil { if err != nil {
log.Println(err) logger.Error("[Controller:UpdateSettings] %v", err)
response.HTML().Render("settings", args.Merge(tplParams{ response.HTML().Render("settings", args.Merge(tplParams{
"form": settingsForm, "form": settingsForm,
"errorMessage": "Unable to update this user.", "errorMessage": "Unable to update this user.",

View file

@ -6,9 +6,9 @@ package controller
import ( import (
"encoding/base64" "encoding/base64"
"log"
"time" "time"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/server/core" "github.com/miniflux/miniflux/server/core"
"github.com/miniflux/miniflux/server/static" "github.com/miniflux/miniflux/server/static"
) )
@ -36,7 +36,7 @@ func (c *Controller) Javascript(ctx *core.Context, request *core.Request, respon
func (c *Controller) Favicon(ctx *core.Context, request *core.Request, response *core.Response) { func (c *Controller) Favicon(ctx *core.Context, request *core.Request, response *core.Response) {
blob, err := base64.StdEncoding.DecodeString(static.Binaries["favicon.ico"]) blob, err := base64.StdEncoding.DecodeString(static.Binaries["favicon.ico"])
if err != nil { if err != nil {
log.Println(err) logger.Error("[Controller:Favicon] %v", err)
response.HTML().NotFound() response.HTML().NotFound()
return return
} }

View file

@ -5,8 +5,7 @@
package controller package controller
import ( import (
"log" "github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/reader/subscription" "github.com/miniflux/miniflux/reader/subscription"
"github.com/miniflux/miniflux/server/core" "github.com/miniflux/miniflux/server/core"
@ -62,7 +61,7 @@ func (c *Controller) SubmitSubscription(ctx *core.Context, request *core.Request
subscriptions, err := subscription.FindSubscriptions(subscriptionForm.URL) subscriptions, err := subscription.FindSubscriptions(subscriptionForm.URL)
if err != nil { if err != nil {
log.Println(err) logger.Error("[Controller:SubmitSubscription] %v", err)
response.HTML().Render("add_subscription", args.Merge(tplParams{ response.HTML().Render("add_subscription", args.Merge(tplParams{
"form": subscriptionForm, "form": subscriptionForm,
"errorMessage": err, "errorMessage": err,
@ -70,7 +69,7 @@ func (c *Controller) SubmitSubscription(ctx *core.Context, request *core.Request
return return
} }
log.Println("[UI:SubmitSubscription]", subscriptions) logger.Info("[UI:SubmitSubscription] %s", subscriptions)
n := len(subscriptions) n := len(subscriptions)
switch { switch {

View file

@ -6,8 +6,8 @@ package controller
import ( import (
"errors" "errors"
"log"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/server/core" "github.com/miniflux/miniflux/server/core"
"github.com/miniflux/miniflux/server/ui/form" "github.com/miniflux/miniflux/server/ui/form"
@ -97,7 +97,7 @@ func (c *Controller) SaveUser(ctx *core.Context, request *core.Request, response
newUser := userForm.ToUser() newUser := userForm.ToUser()
if err := c.store.CreateUser(newUser); err != nil { if err := c.store.CreateUser(newUser); err != nil {
log.Println(err) logger.Error("[Controller:SaveUser] %v", err)
response.HTML().Render("edit_user", args.Merge(tplParams{ response.HTML().Render("edit_user", args.Merge(tplParams{
"menu": "settings", "menu": "settings",
"form": userForm, "form": userForm,
@ -182,7 +182,7 @@ func (c *Controller) UpdateUser(ctx *core.Context, request *core.Request, respon
userForm.Merge(selectedUser) userForm.Merge(selectedUser)
if err := c.store.UpdateUser(selectedUser); err != nil { if err := c.store.UpdateUser(selectedUser); err != nil {
log.Println(err) logger.Error("[Controller:UpdateUser] %v", err)
response.HTML().Render("edit_user", args.Merge(tplParams{ response.HTML().Render("edit_user", args.Merge(tplParams{
"menu": "settings", "menu": "settings",
"selected_user": selectedUser, "selected_user": selectedUser,

View file

@ -1,5 +1,5 @@
// Code generated by go generate; DO NOT EDIT. // Code generated by go generate; DO NOT EDIT.
// 2017-12-12 21:44:02.647917692 -0800 PST m=+0.002328395 // 2017-12-15 18:49:24.029844239 -0800 PST m=+0.002440111
package sql package sql

View file

@ -7,10 +7,10 @@ package storage
import ( import (
"errors" "errors"
"fmt" "fmt"
"log"
"time" "time"
"github.com/miniflux/miniflux/helper" "github.com/miniflux/miniflux/helper"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/model" "github.com/miniflux/miniflux/model"
"github.com/lib/pq" "github.com/lib/pq"
@ -137,7 +137,7 @@ func (s *Storage) UpdateEntries(userID, feedID int64, entries model.Entries) (er
} }
if err := s.CleanupEntries(feedID, entryHashes); err != nil { if err := s.CleanupEntries(feedID, entryHashes); err != nil {
log.Println(err) logger.Error("[Storage:CleanupEntries] %v", err)
} }
return nil return nil

View file

@ -68,9 +68,9 @@ func (s *Storage) Integration(userID int64) (*model.Integration, error) {
) )
switch { switch {
case err == sql.ErrNoRows: case err == sql.ErrNoRows:
return nil, nil return &integration, nil
case err != nil: case err != nil:
return nil, fmt.Errorf("unable to fetch integration row: %v", err) return &integration, fmt.Errorf("unable to fetch integration row: %v", err)
} }
return &integration, nil return &integration, nil

View file

@ -6,9 +6,9 @@ package storage
import ( import (
"fmt" "fmt"
"log"
"strconv" "strconv"
"github.com/miniflux/miniflux/logger"
"github.com/miniflux/miniflux/sql" "github.com/miniflux/miniflux/sql"
) )
@ -27,7 +27,7 @@ func (s *Storage) Migrate() {
tx, err := s.db.Begin() tx, err := s.db.Begin()
if err != nil { if err != nil {
log.Fatalln(err) logger.Fatal("[Storage:Migrate] %v", err)
} }
rawSQL := sql.SqlMap["schema_version_"+strconv.Itoa(version)] rawSQL := sql.SqlMap["schema_version_"+strconv.Itoa(version)]
@ -35,21 +35,21 @@ func (s *Storage) Migrate() {
_, err = tx.Exec(rawSQL) _, err = tx.Exec(rawSQL)
if err != nil { if err != nil {
tx.Rollback() tx.Rollback()
log.Fatalln(err) logger.Fatal("[Storage:Migrate] %v", err)
} }
if _, err := tx.Exec(`delete from schema_version`); err != nil { if _, err := tx.Exec(`delete from schema_version`); err != nil {
tx.Rollback() tx.Rollback()
log.Fatalln(err) logger.Fatal("[Storage:Migrate] %v", err)
} }
if _, err := tx.Exec(`insert into schema_version (version) values($1)`, version); err != nil { if _, err := tx.Exec(`insert into schema_version (version) values($1)`, version); err != nil {
tx.Rollback() tx.Rollback()
log.Fatalln(err) logger.Fatal("[Storage:Migrate] %v", err)
} }
if err := tx.Commit(); err != nil { if err := tx.Commit(); err != nil {
log.Fatalln(err) logger.Fatal("[Storage:Migrate] %v", err)
} }
} }
} }

View file

@ -6,10 +6,10 @@ package storage
import ( import (
"database/sql" "database/sql"
"log"
// Postgresql driver import // Postgresql driver import
_ "github.com/lib/pq" _ "github.com/lib/pq"
"github.com/miniflux/miniflux/logger"
) )
// Storage handles all operations related to the database. // Storage handles all operations related to the database.
@ -26,7 +26,7 @@ func (s *Storage) Close() {
func NewStorage(databaseURL string, maxOpenConns int) *Storage { func NewStorage(databaseURL string, maxOpenConns int) *Storage {
db, err := sql.Open("postgres", databaseURL) db, err := sql.Open("postgres", databaseURL)
if err != nil { if err != nil {
log.Fatalf("Unable to connect to the database: %v", err) logger.Fatal("[Storage] Unable to connect to the database: %v", err)
} }
db.SetMaxOpenConns(maxOpenConns) db.SetMaxOpenConns(maxOpenConns)

View file

@ -8,7 +8,6 @@ import (
"database/sql" "database/sql"
"errors" "errors"
"fmt" "fmt"
"log"
"strings" "strings"
"time" "time"
@ -113,7 +112,7 @@ func (s *Storage) RemoveExtraField(userID int64, field string) error {
// UpdateUser updates a user. // UpdateUser updates a user.
func (s *Storage) UpdateUser(user *model.User) error { func (s *Storage) UpdateUser(user *model.User) error {
defer helper.ExecutionTime(time.Now(), fmt.Sprintf("[Storage:UpdateUser] userID=%d", user.ID)) defer helper.ExecutionTime(time.Now(), fmt.Sprintf("[Storage:UpdateUser] userID=%d", user.ID))
log.Println(user.EntryDirection)
if user.Password != "" { if user.Password != "" {
hashedPassword, err := hashPassword(user.Password) hashedPassword, err := hashPassword(user.Password)
if err != nil { if err != nil {