ref: e50b9d8ac1c69aa16cf45b1e4ff95b22d535adb7
parent: 2fa3761ec993657330d5b9ddbaaab1f58797fb61
author: spf13 <steve.francia@gmail.com>
date: Mon Mar 31 09:23:34 EDT 2014
Adding support for logging & verbose logging. Consolidation of error handling. Integration of jWalterWeatherman library. Fixed #137
--- a/commands/hugo.go
+++ b/commands/hugo.go
@@ -15,12 +15,6 @@
import (
"fmt"
- "github.com/mostafah/fsync"
- "github.com/spf13/cobra"
- "github.com/spf13/hugo/hugolib"
- "github.com/spf13/hugo/utils"
- "github.com/spf13/hugo/watcher"
- "github.com/spf13/nitro"
"os"
"path/filepath"
"runtime"
@@ -27,6 +21,14 @@
"strings"
"sync"
"time"
+
+ "github.com/mostafah/fsync"
+ "github.com/spf13/cobra"
+ "github.com/spf13/hugo/hugolib"
+ "github.com/spf13/hugo/utils"
+ "github.com/spf13/hugo/watcher"
+ jww "github.com/spf13/jwalterweatherman"
+ "github.com/spf13/nitro"
)
var Config *hugolib.Config
@@ -44,8 +46,8 @@
}
var hugoCmdV *cobra.Command
-var BuildWatch, Draft, UglyUrls, Verbose bool
-var Source, Destination, BaseUrl, CfgFile string
+var BuildWatch, Draft, UglyUrls, Verbose, Logging, VerboseLog bool
+var Source, Destination, BaseUrl, CfgFile, LogFile string
func Execute() {AddCommands()
@@ -67,6 +69,9 @@
HugoCmd.PersistentFlags().BoolVar(&UglyUrls, "uglyurls", false, "if true, use /filename.html instead of /filename/")
HugoCmd.PersistentFlags().StringVarP(&BaseUrl, "base-url", "b", "", "hostname (and path) to the root eg. http://spf13.com/")
HugoCmd.PersistentFlags().StringVar(&CfgFile, "config", "", "config file (default is path/config.yaml|json|toml)")
+ HugoCmd.PersistentFlags().BoolVar(&Logging, "log", false, "Enable Logging")
+ HugoCmd.PersistentFlags().StringVar(&LogFile, "logfile", "", "Log File path (if set, logging enabled automatically)")
+ HugoCmd.PersistentFlags().BoolVar(&VerboseLog, "verboselog", false, "verbose logging")
HugoCmd.PersistentFlags().BoolVar(&nitro.AnalysisOn, "stepAnalysis", false, "display memory and timing of different steps of the program")
HugoCmd.Flags().BoolVarP(&BuildWatch, "watch", "w", false, "watch filesystem for changes and recreate as needed")
hugoCmdV = HugoCmd
@@ -86,6 +91,11 @@
if hugoCmdV.PersistentFlags().Lookup("verbose").Changed {Config.Verbose = Verbose
}
+
+ if hugoCmdV.PersistentFlags().Lookup("logfile").Changed {+ Config.LogFile = LogFile
+ }
+
if BaseUrl != "" {Config.BaseUrl = BaseUrl
}
@@ -92,6 +102,24 @@
if Destination != "" {Config.PublishDir = Destination
}
+
+ if VerboseLog || Logging || Config.LogFile != "" {+ if Config.LogFile != "" {+ jww.SetLogFile(Config.LogFile)
+ } else {+ jww.UseTempLogFile("hugo")+ }
+ } else {+ jww.DiscardLogging()
+ }
+
+ if Config.Verbose {+ jww.SetStdoutThreshold(jww.LevelDebug)
+ }
+
+ if VerboseLog {+ jww.SetLogThreshold(jww.LevelDebug)
+ }
}
func build(watches ...bool) {@@ -103,8 +131,8 @@
utils.StopOnErr(buildSite(BuildWatch || watch))
if BuildWatch {- fmt.Println("Watching for changes in", Config.GetAbsPath(Config.ContentDir))- fmt.Println("Press ctrl+c to stop")+ jww.FEEDBACK.Println("Watching for changes in", Config.GetAbsPath(Config.ContentDir))+ jww.FEEDBACK.Println("Press ctrl+c to stop")utils.CheckErr(NewWatcher(0))
}
}
@@ -123,7 +151,7 @@
var a []string
walker := func(path string, fi os.FileInfo, err error) error { if err != nil {- fmt.Println("Walker: ", err)+ jww.ERROR.Println("Walker: ", err)return nil
}
@@ -151,7 +179,7 @@
return
}
site.Stats()
- fmt.Printf("in %v ms\n", int(1000*time.Since(startTime).Seconds()))+ jww.FEEDBACK.Printf("in %v ms\n", int(1000*time.Since(startTime).Seconds()))return nil
}
@@ -182,9 +210,7 @@
for { select {case evs := <-watcher.Event:
- if Verbose {- fmt.Println(evs)
- }
+ jww.INFO.Println(evs)
static_changed := false
dynamic_changed := false
@@ -214,7 +240,7 @@
if static_changed { fmt.Print("Static file changed, syncing\n\n")- utils.CheckErr(copyStatic(), fmt.Sprintf("Error copying static files to %s", Config.GetAbsPath(Config.PublishDir)))+ utils.StopOnErr(copyStatic(), fmt.Sprintf("Error copying static files to %s", Config.GetAbsPath(Config.PublishDir)))}
if dynamic_changed {--- a/commands/limit_darwin.go
+++ b/commands/limit_darwin.go
@@ -15,9 +15,10 @@
package commands
import (
- "fmt"
- "github.com/spf13/cobra"
"syscall"
+
+ "github.com/spf13/cobra"
+ jww "github.com/spf13/jwalterweatherman"
)
func init() {@@ -33,22 +34,22 @@
var rLimit syscall.Rlimit
err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
if err != nil {- fmt.Println("Error Getting Rlimit ", err)+ jww.ERROR.Println("Error Getting Rlimit ", err)}
- fmt.Println("Current rLimit:", rLimit)+ jww.FEEDBACK.Println("Current rLimit:", rLimit)- fmt.Println("Attempting to increase limit")+ jww.FEEDBACK.Println("Attempting to increase limit")rLimit.Max = 999999
rLimit.Cur = 999999
err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
if err != nil {- fmt.Println("Error Setting rLimit ", err)+ jww.ERROR.Println("Error Setting rLimit ", err)}
err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
if err != nil {- fmt.Println("Error Getting rLimit ", err)+ jww.ERROR.Println("Error Getting rLimit ", err)}
- fmt.Println("rLimit after change:", rLimit)+ jww.FEEDBACK.Println("rLimit after change:", rLimit)},
}
@@ -56,7 +57,7 @@
var rLimit syscall.Rlimit
err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
if err != nil {- fmt.Println("Unable to obtain rLimit", err)+ jww.ERROR.Println("Unable to obtain rLimit", err)}
if rLimit.Cur < rLimit.Max {rLimit.Max = 999999
@@ -63,7 +64,7 @@
rLimit.Cur = 999999
err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
if err != nil {- fmt.Println("Unable to increase number of open files limit", err)+ jww.ERROR.Println("Unable to increase number of open files limit", err)}
}
}
--- a/commands/server.go
+++ b/commands/server.go
@@ -15,11 +15,13 @@
import (
"fmt"
- "github.com/spf13/cobra"
"net/http"
"os"
"strconv"
"strings"
+
+ "github.com/spf13/cobra"
+ jww "github.com/spf13/jwalterweatherman"
)
var serverPort int
@@ -62,7 +64,7 @@
// Watch runs its own server as part of the routine
if serverWatch {- fmt.Println("Watching for changes in", Config.GetAbsPath(Config.ContentDir))+ jww.FEEDBACK.Println("Watching for changes in", Config.GetAbsPath(Config.ContentDir))err := NewWatcher(serverPort)
if err != nil {fmt.Println(err)
@@ -73,14 +75,12 @@
}
func serve(port int) {- if Verbose {- fmt.Println("Serving pages from " + Config.GetAbsPath(Config.PublishDir))- }
+ jww.FEEDBACK.Println("Serving pages from " + Config.GetAbsPath(Config.PublishDir)) if BaseUrl == "" {- fmt.Printf("Web Server is available at %s\n", Config.BaseUrl)+ jww.FEEDBACK.Printf("Web Server is available at %s\n", Config.BaseUrl) } else {- fmt.Printf("Web Server is available at http://localhost:%v\n", port)+ jww.FEEDBACK.Printf("Web Server is available at http://localhost:%v\n", port)}
fmt.Println("Press ctrl+c to stop")@@ -87,7 +87,7 @@
err := http.ListenAndServe(":"+strconv.Itoa(port), http.FileServer(http.Dir(Config.GetAbsPath(Config.PublishDir)))) if err != nil {- fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error())
+ jww.ERROR.Printf("Error: %s\n", err.Error())os.Exit(1)
}
}
--- a/commands/version.go
+++ b/commands/version.go
@@ -15,6 +15,7 @@
import (
"fmt"
+
"github.com/spf13/cobra"
)
--- a/docs/content/overview/usage.md
+++ b/docs/content/overview/usage.md
@@ -31,9 +31,12 @@
-D, --build-drafts=false: include content marked as draft
--config="": config file (default is path/config.yaml|json|toml)
-d, --destination="": filesystem path to write files to
+ --log=false: Enable Logging
+ --logfile="": Log File path (if set, logging enabled automatically)
-s, --source="": filesystem path to read files relative from
--uglyurls=false: if true, use /filename.html instead of /filename/
-v, --verbose=false: verbose output
+ --verboselog=false: verbose logging
-w, --watch=false: watch filesystem for changes and recreate as needed
Use "hugo help [command]" for more information about that command.
--- a/helpers/pygments.go
+++ b/helpers/pygments.go
@@ -15,9 +15,10 @@
import (
"bytes"
- "log"
"os/exec"
"strings"
+
+ jww "github.com/spf13/jwalterweatherman"
)
func Highlight(code string, lexer string) string {@@ -24,7 +25,8 @@
var pygmentsBin = "pygmentize"
if _, err := exec.LookPath(pygmentsBin); err != nil {- log.Print("Highlighting requries Pygments to be installed and in the path")+
+ jww.WARN.Println("Highlighting requries Pygments to be installed and in the path")return code
}
@@ -37,7 +39,7 @@
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {- log.Print(stderr.String())
+ jww.ERROR.Print(stderr.String())
return code
}
--- a/helpers/url.go
+++ b/helpers/url.go
@@ -14,12 +14,9 @@
package helpers
import (
- "fmt"
"net/url"
"path"
)
-
-var _ = fmt.Println
// Similar to MakePath, but with Unicode handling
// Example:
--- a/hugolib/config.go
+++ b/hugolib/config.go
@@ -16,14 +16,16 @@
import (
"encoding/json"
"fmt"
- "github.com/BurntSushi/toml"
- "github.com/spf13/hugo/helpers"
"io/ioutil"
- "launchpad.net/goyaml"
"os"
"path"
"path/filepath"
"strings"
+
+ "github.com/BurntSushi/toml"
+ "github.com/spf13/hugo/helpers"
+ jww "github.com/spf13/jwalterweatherman"
+ "launchpad.net/goyaml"
)
// config file items
@@ -30,7 +32,7 @@
type Config struct {ContentDir, PublishDir, BaseUrl, StaticDir string
Path, CacheDir, LayoutDir, DefaultLayout string
- ConfigFile string
+ ConfigFile, LogFile string
Title string
Indexes map[string]string // singular, plural
ProcessFilters map[string][]string
@@ -50,8 +52,8 @@
c.ConfigFile = cfg
if err != nil {- fmt.Printf("%v", err)- fmt.Println(" using defaults instead")+ jww.ERROR.Printf("%v", err)+ jww.FEEDBACK.Println("using defaults instead")}
// set defaults
@@ -92,19 +94,19 @@
switch path.Ext(c.ConfigFile) {case ".yaml":
if err := goyaml.Unmarshal(file, &c); err != nil {- fmt.Printf("Error parsing config: %s", err)+ jww.ERROR.Printf("Error parsing config: %s", err)os.Exit(1)
}
case ".json":
if err := json.Unmarshal(file, &c); err != nil {- fmt.Printf("Error parsing config: %s", err)+ jww.ERROR.Printf("Error parsing config: %s", err)os.Exit(1)
}
case ".toml":
if _, err := toml.Decode(string(file), &c); err != nil {- fmt.Printf("Error parsing config: %s", err)+ jww.ERROR.Printf("Error parsing config: %s", err)os.Exit(1)
}
}
@@ -115,13 +117,13 @@
if p == "" {path, err := findPath()
if err != nil {- fmt.Printf("Error finding path: %s", err)+ jww.ERROR.Printf("Error finding path: %s", err)}
c.Path = path
} else {path, err := filepath.Abs(p)
if err != nil {- fmt.Printf("Error finding path: %s", err)+ jww.ERROR.Printf("Error finding path: %s", err)}
c.Path = path
}
--- a/hugolib/metadata.go
+++ b/hugolib/metadata.go
@@ -3,9 +3,10 @@
import (
"errors"
"fmt"
- "os"
"strconv"
"time"
+
+ jww "github.com/spf13/jwalterweatherman"
)
func interfaceToTime(i interface{}) time.Time {@@ -17,9 +18,9 @@
if e == nil {return d
}
- errorln("Could not parse Date/Time format:", e)+ jww.ERROR.Println("Could not parse Date/Time format:", e)default:
- errorln("Only Time is supported for this key")+ jww.ERROR.Println("Only Time is supported for this key")}
return *new(time.Time)
@@ -53,11 +54,6 @@
})
}
-// TODO remove this and return a proper error.
-func errorln(str string, a ...interface{}) {- fmt.Fprintln(os.Stderr, str, a)
-}
-
func parseDateWith(s string, dates []string) (d time.Time, e error) { for _, dateType := range dates { if d, e = time.Parse(dateType, s); e == nil {@@ -77,7 +73,7 @@
}
return false
default:
- errorln("Only Boolean values are supported for this YAML key")+ jww.ERROR.Println("Only Boolean values are supported for this YAML key")}
return false
@@ -109,11 +105,11 @@
if err == nil {return float64(v)
} else {- errorln("Only Floats are supported for this key\nErr:", err)+ jww.ERROR.Println("Only Floats are supported for this key\nErr:", err)}
default:
- errorln("Only Floats are supported for this key")+ jww.ERROR.Println("Only Floats are supported for this key")}
return 0.0
@@ -136,10 +132,10 @@
if err == nil {return int(v)
} else {- errorln("Only Ints are supported for this key\nErr:", err)+ jww.ERROR.Println("Only Ints are supported for this key\nErr:", err)}
default:
- errorln("Only Ints are supported for this key")+ jww.ERROR.Println("Only Ints are supported for this key")}
return 0
@@ -154,7 +150,7 @@
case int:
return strconv.FormatInt(int64(i.(int)), 10)
default:
- errorln(fmt.Sprintf("Only Strings are supported for this key (got type '%T'): %s", s, s))+ jww.ERROR.Println(fmt.Sprintf("Only Strings are supported for this key (got type '%T'): %s", s, s))}
return ""
--- a/hugolib/page.go
+++ b/hugolib/page.go
@@ -17,19 +17,21 @@
"bytes"
"errors"
"fmt"
+ "html/template"
+ "io"
+ "net/url"
+ "path"
+ "strings"
+ "time"
+
"github.com/BurntSushi/toml"
"github.com/spf13/hugo/helpers"
"github.com/spf13/hugo/parser"
"github.com/spf13/hugo/template/bundle"
+ jww "github.com/spf13/jwalterweatherman"
"github.com/theplant/blackfriday"
- "html/template"
- "io"
"launchpad.net/goyaml"
json "launchpad.net/rjson"
- "net/url"
- "path"
- "strings"
- "time"
)
type Page struct {@@ -142,6 +144,8 @@
File: File{FileName: filename, Extension: "html"}, Node: Node{Keywords: make([]string, 10, 30)}, Params: make(map[string]interface{})}+
+ jww.DEBUG.Println("Reading from", page.File.FileName) page.Date, _ = time.Parse("20060102", "20080101")page.guessSection()
return &page
@@ -212,6 +216,7 @@
// Parse for metadata & body
if err = p.parse(buf); err != nil {+ jww.ERROR.Print(err)
return
}
--- a/hugolib/shortcode.go
+++ b/hugolib/shortcode.go
@@ -15,16 +15,15 @@
import (
"bytes"
- "fmt"
- "github.com/spf13/hugo/template/bundle"
"html/template"
"reflect"
"strings"
"unicode"
+
+ "github.com/spf13/hugo/template/bundle"
+ jww "github.com/spf13/jwalterweatherman"
)
-var _ = fmt.Println
-
type ShortcodeFunc func([]string) string
type Shortcode struct {@@ -296,8 +295,8 @@
buffer := new(bytes.Buffer)
err := tmpl.Execute(buffer, data)
if err != nil {- fmt.Println("error processing shortcode", tmpl.Name(), "\n ERR:", err)- fmt.Println(data)
+ jww.ERROR.Println("error processing shortcode", tmpl.Name(), "\n ERR:", err)+ jww.WARN.Println(data)
}
return buffer.String()
}
--- a/hugolib/site.go
+++ b/hugolib/site.go
@@ -14,15 +14,8 @@
package hugolib
import (
- "bitbucket.org/pkg/inflect"
"bytes"
"fmt"
- "github.com/spf13/hugo/helpers"
- "github.com/spf13/hugo/source"
- "github.com/spf13/hugo/target"
- "github.com/spf13/hugo/template/bundle"
- "github.com/spf13/hugo/transform"
- "github.com/spf13/nitro"
"html/template"
"io"
"os"
@@ -29,6 +22,15 @@
"strings"
"sync"
"time"
+
+ "bitbucket.org/pkg/inflect"
+ "github.com/spf13/hugo/helpers"
+ "github.com/spf13/hugo/source"
+ "github.com/spf13/hugo/target"
+ "github.com/spf13/hugo/template/bundle"
+ "github.com/spf13/hugo/transform"
+ jww "github.com/spf13/jwalterweatherman"
+ "github.com/spf13/nitro"
)
var _ = transform.AbsURL
@@ -104,9 +106,9 @@
return
}
if err = s.Render(); err != nil {- fmt.Printf("Error rendering site: %s\nAvailable templates:\n", err)+ jww.ERROR.Printf("Error rendering site: %s\nAvailable templates:\n", err) for _, template := range s.Tmpl.Templates() {- fmt.Printf("\t%s\n", template.Name())+ jww.ERROR.Printf("\t%s\n", template.Name())}
return
}
@@ -190,7 +192,7 @@
func (s *Site) checkDescriptions() { for _, p := range s.Pages { if len(p.Description) < 60 {- fmt.Println(p.FileName + " ")
+ jww.FEEDBACK.Println(p.FileName + " ")
}
}
}
@@ -309,9 +311,7 @@
s.Indexes[plural].Add(idx, x)
}
} else {- if s.Config.Verbose {- fmt.Fprintf(os.Stderr, "Invalid %s in %s\n", plural, p.File.FileName)
- }
+ jww.ERROR.Printf("Invalid %s in %s\n", plural, p.File.FileName)}
}
}
@@ -533,9 +533,9 @@
}
func (s *Site) Stats() {- fmt.Printf("%d pages created \n", len(s.Pages))+ jww.FEEDBACK.Printf("%d pages created \n", len(s.Pages)) for _, pl := range s.Config.Indexes {- fmt.Printf("%d %s index created\n", len(s.Indexes[pl]), pl)+ jww.FEEDBACK.Printf("%d %s index created\n", len(s.Indexes[pl]), pl)}
}
@@ -572,9 +572,7 @@
layout := s.findFirstLayout(layouts...)
if layout == "" {- if s.Config.Verbose {- fmt.Printf("Unable to locate layout: %s\n", layouts)- }
+ jww.WARN.Printf("Unable to locate layout: %s\n", layouts)return
}
@@ -601,7 +599,7 @@
err = s.renderThing(d, layout, renderBuffer)
if err != nil {// Behavior here should be dependent on if running in server or watch mode.
- fmt.Println(fmt.Errorf("Rendering error: %v", err))+ jww.ERROR.Println(fmt.Errorf("Rendering error: %v", err)) if !s.Running() {os.Exit(-1)
}
@@ -631,7 +629,6 @@
if s.Tmpl.Lookup(layout) == nil { return fmt.Errorf("Layout not found: %s", layout)}
- //defer w.Close()
return s.Tmpl.ExecuteTemplate(w, layout, d)
}
@@ -652,9 +649,7 @@
func (s *Site) WritePublic(path string, reader io.Reader) (err error) {s.initTarget()
- if s.Config.Verbose {- fmt.Println(path)
- }
+ jww.DEBUG.Println("writing to", path)return s.Target.Publish(path, reader)
}
@@ -666,9 +661,7 @@
}
}
- if s.Config.Verbose {- fmt.Println(path)
- }
+ jww.DEBUG.Println("alias created at", path)return s.Alias.Publish(path, permalink)
}
--- a/hugolib/summary.go
+++ b/hugolib/summary.go
@@ -2,9 +2,10 @@
import (
"bytes"
- "fmt"
"os/exec"
"strings"
+
+ jww "github.com/spf13/jwalterweatherman"
)
var summaryLength = 70
@@ -62,7 +63,7 @@
var out bytes.Buffer
cmd.Stdout = &out
if err := cmd.Run(); err != nil {- fmt.Println(err)
+ jww.ERROR.Println(err)
}
rstLines := strings.Split(out.String(), "\n")
--- a/main.go
+++ b/main.go
@@ -14,8 +14,9 @@
package main
import (
- "github.com/spf13/hugo/commands"
"runtime"
+
+ "github.com/spf13/hugo/commands"
)
func main() {--- a/utils/utils.go
+++ b/utils/utils.go
@@ -1,22 +1,24 @@
package utils
import (
- "log"
"os"
+
+ jww "github.com/spf13/jwalterweatherman"
)
func CheckErr(err error, s ...string) { if err != nil { for _, message := range s {- log.Fatalf(message)
+ jww.ERROR.Println(message)
}
- log.Fatalf("Fatal Error: %v", err)}
}
func StopOnErr(err error, s ...string) { if err != nil {- CheckErr(err, s...)
+ for _, message := range s {+ jww.CRITICAL.Println(message)
+ }
os.Exit(-1)
}
}
--
⑨