Browse Source

log: start using gopkg.in/clog.v1

pull/2935/merge
Unknwon 8 years ago
parent
commit
eb66060cd7
No known key found for this signature in database
GPG Key ID: FB9F411CDD69BEC1
  1. 31
      cmd/serve.go
  2. 10
      cmd/update.go
  3. 2
      cmd/web.go
  4. 51
      conf/app.ini
  5. 2
      gogs.go
  6. 2
      models/access.go
  7. 2
      models/action.go
  8. 2
      models/admin.go
  9. 2
      models/git_diff.go
  10. 2
      models/issue.go
  11. 2
      models/issue_comment.go
  12. 2
      models/issue_mail.go
  13. 2
      models/login_source.go
  14. 2
      models/migrations/migrations.go
  15. 2
      models/org.go
  16. 2
      models/pull.go
  17. 2
      models/repo.go
  18. 2
      models/repo_editor.go
  19. 2
      models/repo_mirror.go
  20. 2
      models/ssh_key.go
  21. 6
      models/update.go
  22. 2
      models/user.go
  23. 2
      models/webhook.go
  24. 2
      modules/auth/auth.go
  25. 43
      modules/auth/ldap/ldap.go
  26. 8
      modules/base/tool.go
  27. 4
      modules/bindata/bindata.go
  28. 2
      modules/context/api.go
  29. 8
      modules/context/context.go
  30. 4
      modules/context/repo.go
  31. 3
      modules/cron/cron.go
  32. 104
      modules/log/conn.go
  33. 73
      modules/log/console.go
  34. 243
      modules/log/file.go
  35. 312
      modules/log/log.go
  36. 87
      modules/log/smtp.go
  37. 2
      modules/mailer/mail.go
  38. 2
      modules/mailer/mailer.go
  39. 2
      modules/process/manager.go
  40. 117
      modules/setting/setting.go
  41. 2
      modules/ssh/ssh.go
  42. 2
      modules/template/template.go
  43. 8
      routers/admin/admin.go
  44. 2
      routers/admin/auths.go
  45. 2
      routers/admin/notice.go
  46. 3
      routers/admin/repos.go
  47. 2
      routers/admin/users.go
  48. 3
      routers/api/v1/admin/user.go
  49. 3
      routers/api/v1/repo/repo.go
  50. 3
      routers/install.go
  51. 2
      routers/org/members.go
  52. 3
      routers/org/org.go
  53. 3
      routers/org/setting.go
  54. 2
      routers/org/teams.go
  55. 3
      routers/repo/branch.go
  56. 3
      routers/repo/editor.go
  57. 19
      routers/repo/http.go
  58. 2
      routers/repo/issue.go
  59. 2
      routers/repo/pull.go
  60. 3
      routers/repo/release.go
  61. 2
      routers/repo/repo.go
  62. 3
      routers/repo/setting.go
  63. 2
      routers/repo/view.go
  64. 2
      routers/user/auth.go
  65. 2
      routers/user/setting.go
  66. 2
      templates/.VERSION

31
cmd/serve.go

@ -17,11 +17,11 @@ import (
git "github.com/gogits/git-module"
gouuid "github.com/satori/go.uuid"
"github.com/urfave/cli"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/httplib"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)
@ -42,7 +42,15 @@ var CmdServ = cli.Command{
func setup(logPath string) {
setting.NewContext()
setting.NewService()
log.NewGitLogger(filepath.Join(setting.LogRootPath, logPath))
log.New(log.FILE, log.FileConfig{
Filename: filepath.Join(setting.LogRootPath, logPath),
FileRotationConfig: log.FileRotationConfig{
Rotate: true,
Daily: true,
MaxDays: 3,
},
})
log.Delete(log.CONSOLE) // Remove primary logger
models.LoadConfigs()
@ -95,11 +103,10 @@ func fail(userMessage, logMessage string, args ...interface{}) {
if !setting.ProdMode {
fmt.Fprintf(os.Stderr, logMessage+"\n", args...)
}
log.GitLogger.Fatal(3, logMessage, args...)
return
log.Fatal(3, logMessage, args...)
}
log.GitLogger.Close()
log.Shutdown()
os.Exit(1)
}
@ -107,12 +114,12 @@ func handleUpdateTask(uuid string, user, repoUser *models.User, reponame string,
task, err := models.GetUpdateTaskByUUID(uuid)
if err != nil {
if models.IsErrUpdateTaskNotExist(err) {
log.GitLogger.Trace("No update task is presented: %s", uuid)
log.Trace("No update task is presented: %s", uuid)
return
}
log.GitLogger.Fatal(2, "GetUpdateTaskByUUID: %v", err)
log.Fatal(2, "GetUpdateTaskByUUID: %v", err)
} else if err = models.DeleteUpdateTaskByUUID(uuid); err != nil {
log.GitLogger.Fatal(2, "DeleteUpdateTaskByUUID: %v", err)
log.Fatal(2, "DeleteUpdateTaskByUUID: %v", err)
}
if isWiki {
@ -128,13 +135,13 @@ func handleUpdateTask(uuid string, user, repoUser *models.User, reponame string,
RepoUserName: repoUser.Name,
RepoName: reponame,
}); err != nil {
log.GitLogger.Error(2, "Update: %v", err)
log.Error(2, "Update: %v", err)
}
// Ask for running deliver hook and test pull request tasks.
reqURL := setting.LocalURL + repoUser.Name + "/" + reponame + "/tasks/trigger?branch=" +
strings.TrimPrefix(task.RefName, git.BRANCH_PREFIX) + "&secret=" + base.EncodeMD5(repoUser.Salt) + "&pusher=" + com.ToStr(user.ID)
log.GitLogger.Trace("Trigger task: %s", reqURL)
log.Trace("Trigger task: %s", reqURL)
resp, err := httplib.Head(reqURL).SetTLSClientConfig(&tls.Config{
InsecureSkipVerify: true,
@ -142,10 +149,10 @@ func handleUpdateTask(uuid string, user, repoUser *models.User, reponame string,
if err == nil {
resp.Body.Close()
if resp.StatusCode/100 != 2 {
log.GitLogger.Error(2, "Fail to trigger task: not 2xx response code")
log.Error(2, "Fail to trigger task: not 2xx response code")
}
} else {
log.GitLogger.Error(2, "Fail to trigger task: %v", err)
log.Error(2, "Fail to trigger task: %v", err)
}
}

10
cmd/update.go

@ -8,9 +8,9 @@ import (
"os"
"github.com/urfave/cli"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)
@ -32,15 +32,15 @@ func runUpdate(c *cli.Context) error {
setup("update.log")
if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
log.GitLogger.Trace("SSH_ORIGINAL_COMMAND is empty")
log.Trace("SSH_ORIGINAL_COMMAND is empty")
return nil
}
args := c.Args()
if len(args) != 3 {
log.GitLogger.Fatal(2, "Arguments received are not equal to three")
log.Fatal(2, "Arguments received are not equal to three")
} else if len(args[0]) == 0 {
log.GitLogger.Fatal(2, "First argument 'refName' is empty, shouldn't use")
log.Fatal(2, "First argument 'refName' is empty, shouldn't use")
}
task := models.UpdateTask{
@ -51,7 +51,7 @@ func runUpdate(c *cli.Context) error {
}
if err := models.AddUpdateTask(&task); err != nil {
log.GitLogger.Fatal(2, "AddUpdateTask: %v", err)
log.Fatal(2, "AddUpdateTask: %v", err)
}
return nil

2
cmd/web.go

@ -26,6 +26,7 @@ import (
"github.com/go-xorm/xorm"
"github.com/mcuadros/go-version"
"github.com/urfave/cli"
log "gopkg.in/clog.v1"
"gopkg.in/ini.v1"
"gopkg.in/macaron.v1"
@ -36,7 +37,6 @@ import (
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/bindata"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/mailer"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/modules/template"

51
conf/app.ini

@ -300,12 +300,12 @@ FORMAT =
[log]
ROOT_PATH =
; Either "console", "file", "conn", "smtp" or "database", default is "console"
; Can be "console" and "file", default is "console"
; Use comma to separate multiple modes, e.g. "console, file"
MODE = console
; Buffer length of channel, keep it as it is if you don't know what it is.
BUFFER_LEN = 10000
; Either "Trace", "Debug", "Info", "Warn", "Error", "Critical", default is "Trace"
BUFFER_LEN = 100
; Either "Trace", "Info", "Warn", "Error", "Fatal", default is "Trace"
LEVEL = Trace
; For "console" mode only
@ -315,50 +315,17 @@ LEVEL =
; For "file" mode only
[log.file]
LEVEL =
; This enables automated log rotate(switch of following options), default is true
; This enables automated log rotate (switch of following options)
LOG_ROTATE = true
; Max line number of single file, default is 1000000
MAX_LINES = 1000000
; Segment log daily
DAILY_ROTATE = true
; Max size shift of single file, default is 28 means 1 << 28, 256MB
MAX_SIZE_SHIFT = 28
; Segment log daily, default is true
DAILY_ROTATE = true
; Expired days of log file(delete after max days), default is 7
; Max line number of single file
MAX_LINES = 1000000
; Expired days of log file (delete after max days)
MAX_DAYS = 7
; For "conn" mode only
[log.conn]
LEVEL =
; Reconnect host for every single message, default is false
RECONNECT_ON_MSG = false
; Try to reconnect when connection is lost, default is false
RECONNECT = false
; Either "tcp", "unix" or "udp", default is "tcp"
PROTOCOL = tcp
; Host address
ADDR =
; For "smtp" mode only
[log.smtp]
LEVEL =
; Name displayed in mail title, default is "Diagnostic message from server"
SUBJECT = Diagnostic message from server
; Mail server
HOST =
; Mailer user name and password
USER =
PASSWD =
; Receivers, can be one or more, e.g. 1@example.com,2@example.com
RECEIVERS =
; For "database" mode only
[log.database]
LEVEL =
; Either "mysql" or "postgres"
DRIVER =
; Based on xorm, e.g.: root:root@localhost/gogs?charset=utf8
CONN =
[cron]
; Enable running cron tasks periodically.
ENABLED = true

2
gogs.go

@ -16,7 +16,7 @@ import (
"github.com/gogits/gogs/modules/setting"
)
const APP_VER = "0.9.138.0209"
const APP_VER = "0.9.139.0209"
func init() {
setting.AppVer = APP_VER

2
models/access.go

@ -7,7 +7,7 @@ package models
import (
"fmt"
"github.com/gogits/gogs/modules/log"
log "gopkg.in/clog.v1"
)
type AccessMode int

2
models/action.go

@ -15,12 +15,12 @@ import (
"github.com/Unknwon/com"
"github.com/go-xorm/xorm"
log "gopkg.in/clog.v1"
"github.com/gogits/git-module"
api "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)

2
models/admin.go

@ -13,9 +13,9 @@ import (
"github.com/Unknwon/com"
"github.com/go-xorm/xorm"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)

2
models/git_diff.go

@ -20,11 +20,11 @@ import (
"github.com/sergi/go-diff/diffmatchpatch"
"golang.org/x/net/html/charset"
"golang.org/x/text/transform"
log "gopkg.in/clog.v1"
"github.com/gogits/git-module"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/process"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/modules/template/highlight"

2
models/issue.go

@ -18,9 +18,9 @@ import (
"github.com/go-xorm/xorm"
api "github.com/gogits/go-gogs-client"
gouuid "github.com/satori/go.uuid"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)

2
models/issue_comment.go

@ -11,10 +11,10 @@ import (
"github.com/Unknwon/com"
"github.com/go-xorm/xorm"
log "gopkg.in/clog.v1"
api "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/markdown"
)

2
models/issue_mail.go

@ -8,8 +8,8 @@ import (
"fmt"
"github.com/Unknwon/com"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/mailer"
"github.com/gogits/gogs/modules/markdown"
"github.com/gogits/gogs/modules/setting"

2
models/login_source.go

@ -18,10 +18,10 @@ import (
"github.com/go-macaron/binding"
"github.com/go-xorm/core"
"github.com/go-xorm/xorm"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/modules/auth/ldap"
"github.com/gogits/gogs/modules/auth/pam"
"github.com/gogits/gogs/modules/log"
)
type LoginType int

2
models/migrations/migrations.go

@ -18,10 +18,10 @@ import (
"github.com/Unknwon/com"
"github.com/go-xorm/xorm"
gouuid "github.com/satori/go.uuid"
log "gopkg.in/clog.v1"
"gopkg.in/ini.v1"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)

2
models/org.go

@ -11,9 +11,9 @@ import (
"strings"
"github.com/go-xorm/xorm"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
)
var (

2
models/pull.go

@ -13,11 +13,11 @@ import (
"github.com/Unknwon/com"
"github.com/go-xorm/xorm"
log "gopkg.in/clog.v1"
"github.com/gogits/git-module"
api "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/process"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/modules/sync"

2
models/repo.go

@ -23,13 +23,13 @@ import (
"github.com/Unknwon/com"
"github.com/go-xorm/xorm"
"github.com/mcuadros/go-version"
log "gopkg.in/clog.v1"
"gopkg.in/ini.v1"
git "github.com/gogits/git-module"
api "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/modules/bindata"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/markdown"
"github.com/gogits/gogs/modules/process"
"github.com/gogits/gogs/modules/setting"

2
models/repo_editor.go

@ -17,10 +17,10 @@ import (
"github.com/Unknwon/com"
gouuid "github.com/satori/go.uuid"
log "gopkg.in/clog.v1"
git "github.com/gogits/git-module"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/process"
"github.com/gogits/gogs/modules/setting"
)

2
models/repo_mirror.go

@ -11,11 +11,11 @@ import (
"github.com/Unknwon/com"
"github.com/go-xorm/xorm"
log "gopkg.in/clog.v1"
"gopkg.in/ini.v1"
"github.com/gogits/git-module"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/process"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/modules/sync"

2
models/ssh_key.go

@ -21,9 +21,9 @@ import (
"github.com/Unknwon/com"
"github.com/go-xorm/xorm"
"golang.org/x/crypto/ssh"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/process"
"github.com/gogits/gogs/modules/setting"
)

6
models/update.go

@ -10,9 +10,9 @@ import (
"os/exec"
"strings"
git "github.com/gogits/git-module"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/modules/log"
git "github.com/gogits/git-module"
)
type UpdateTask struct {
@ -101,7 +101,7 @@ func PushUpdate(opts PushUpdateOptions) (err error) {
}
if isDelRef {
log.GitLogger.Info("Reference '%s' has been deleted from '%s/%s' by %s",
log.Trace("Reference '%s' has been deleted from '%s/%s' by %s",
opts.RefFullName, opts.RepoUserName, opts.RepoName, opts.PusherName)
return nil
}

2
models/user.go

@ -25,13 +25,13 @@ import (
"github.com/go-xorm/xorm"
"github.com/nfnt/resize"
"golang.org/x/crypto/pbkdf2"
log "gopkg.in/clog.v1"
"github.com/gogits/git-module"
api "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/modules/avatar"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/markdown"
"github.com/gogits/gogs/modules/setting"
)

2
models/webhook.go

@ -14,11 +14,11 @@ import (
"github.com/go-xorm/xorm"
gouuid "github.com/satori/go.uuid"
log "gopkg.in/clog.v1"
api "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/modules/httplib"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/modules/sync"
)

2
modules/auth/auth.go

@ -13,11 +13,11 @@ import (
"github.com/go-macaron/binding"
"github.com/go-macaron/session"
gouuid "github.com/satori/go.uuid"
log "gopkg.in/clog.v1"
"gopkg.in/macaron.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)

43
modules/auth/ldap/ldap.go

@ -11,9 +11,8 @@ import (
"fmt"
"strings"
log "gopkg.in/clog.v1"
"gopkg.in/ldap.v2"
"github.com/gogits/gogs/modules/log"
)
type SecurityProtocol int
@ -50,7 +49,7 @@ func (ls *Source) sanitizedUserQuery(username string) (string, bool) {
// See http://tools.ietf.org/search/rfc4515
badCharacters := "\x00()*\\"
if strings.ContainsAny(username, badCharacters) {
log.Debug("'%s' contains invalid query characters. Aborting.", username)
log.Trace("Username contains invalid query characters: %s", username)
return "", false
}
@ -61,7 +60,7 @@ func (ls *Source) sanitizedUserDN(username string) (string, bool) {
// See http://tools.ietf.org/search/rfc4514: "special characters"
badCharacters := "\x00()*\\,='\"#+;<>"
if strings.ContainsAny(username, badCharacters) || strings.HasPrefix(username, " ") || strings.HasSuffix(username, " ") {
log.Debug("'%s' contains invalid DN characters. Aborting.", username)
log.Trace("Username contains invalid query characters: %s", username)
return "", false
}
@ -73,12 +72,12 @@ func (ls *Source) findUserDN(l *ldap.Conn, name string) (string, bool) {
if ls.BindDN != "" && ls.BindPassword != "" {
err := l.Bind(ls.BindDN, ls.BindPassword)
if err != nil {
log.Debug("Failed to bind as BindDN[%s]: %v", ls.BindDN, err)
log.Trace("Failed to bind as BindDN '%s': %v", ls.BindDN, err)
return "", false
}
log.Trace("Bound as BindDN %s", ls.BindDN)
log.Trace("Bound as BindDN: %s", ls.BindDN)
} else {
log.Trace("Proceeding with anonymous LDAP search.")
log.Trace("Proceeding with anonymous LDAP search")
}
// A search for the user.
@ -87,7 +86,7 @@ func (ls *Source) findUserDN(l *ldap.Conn, name string) (string, bool) {
return "", false
}
log.Trace("Searching for DN using filter %s and base %s", userFilter, ls.UserBase)
log.Trace("Searching for DN using filter '%s' and base '%s'", userFilter, ls.UserBase)
search := ldap.NewSearchRequest(
ls.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0,
false, userFilter, []string{}, nil)
@ -95,10 +94,10 @@ func (ls *Source) findUserDN(l *ldap.Conn, name string) (string, bool) {
// Ensure we found a user
sr, err := l.Search(search)
if err != nil || len(sr.Entries) < 1 {
log.Debug("Failed search using filter[%s]: %v", userFilter, err)
log.Trace("Failed search using filter '%s': %v", userFilter, err)
return "", false
} else if len(sr.Entries) > 1 {
log.Debug("Filter '%s' returned more than one user.", userFilter)
log.Trace("Filter '%s' returned more than one user", userFilter)
return "", false
}
@ -112,7 +111,7 @@ func (ls *Source) findUserDN(l *ldap.Conn, name string) (string, bool) {
}
func dial(ls *Source) (*ldap.Conn, error) {
log.Trace("Dialing LDAP with security protocol (%v) without verifying: %v", ls.SecurityProtocol, ls.SkipVerify)
log.Trace("Dialing LDAP with security protocol '%v' without verifying: %v", ls.SecurityProtocol, ls.SkipVerify)
tlsCfg := &tls.Config{
ServerName: ls.Host,
@ -141,7 +140,7 @@ func bindUser(l *ldap.Conn, userDN, passwd string) error {
log.Trace("Binding with userDN: %s", userDN)
err := l.Bind(userDN, passwd)
if err != nil {
log.Debug("LDAP auth. failed for %s, reason: %v", userDN, err)
log.Trace("LDAP authentication failed for '%s': %v", userDN, err)
return err
}
log.Trace("Bound successfully with userDN: %s", userDN)
@ -152,12 +151,12 @@ func bindUser(l *ldap.Conn, userDN, passwd string) error {
func (ls *Source) SearchEntry(name, passwd string, directBind bool) (string, string, string, string, bool, bool) {
// See https://tools.ietf.org/search/rfc4513#section-5.1.2
if len(passwd) == 0 {
log.Debug("Auth. failed for %s, password cannot be empty")
log.Trace("authentication failed for '%s' with empty password")
return "", "", "", "", false, false
}
l, err := dial(ls)
if err != nil {
log.Error(4, "LDAP Connect error, %s:%v", ls.Host, err)
log.Error(4, "LDAP connect failed for '%s': %v", ls.Host, err)
ls.Enabled = false
return "", "", "", "", false, false
}
@ -173,7 +172,7 @@ func (ls *Source) SearchEntry(name, passwd string, directBind bool) (string, str
return "", "", "", "", false, false
}
} else {
log.Trace("LDAP will use BindDN.")
log.Trace("LDAP will use BindDN")
var found bool
userDN, found = ls.findUserDN(l, name)
@ -195,7 +194,7 @@ func (ls *Source) SearchEntry(name, passwd string, directBind bool) (string, str
return "", "", "", "", false, false
}
log.Trace("Fetching attributes '%v', '%v', '%v', '%v' with filter %s and base %s", ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail, userFilter, userDN)
log.Trace("Fetching attributes '%v', '%v', '%v', '%v' with filter '%s' and base '%s'", ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail, userFilter, userDN)
search := ldap.NewSearchRequest(
userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
[]string{ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail},
@ -203,13 +202,13 @@ func (ls *Source) SearchEntry(name, passwd string, directBind bool) (string, str
sr, err := l.Search(search)
if err != nil {
log.Error(4, "LDAP Search failed unexpectedly! (%v)", err)
log.Error(4, "LDAP search failed: %v", err)
return "", "", "", "", false, false
} else if len(sr.Entries) < 1 {
if directBind {
log.Error(4, "User filter inhibited user login.")
log.Error(4, "User filter inhibited user login")
} else {
log.Error(4, "LDAP Search failed unexpectedly! (0 entries)")
log.Error(4, "LDAP search failed: 0 entries")
}
return "", "", "", "", false, false
@ -222,7 +221,7 @@ func (ls *Source) SearchEntry(name, passwd string, directBind bool) (string, str
isAdmin := false
if len(ls.AdminFilter) > 0 {
log.Trace("Checking admin with filter %s and base %s", ls.AdminFilter, userDN)
log.Trace("Checking admin with filter '%s' and base '%s'", ls.AdminFilter, userDN)
search = ldap.NewSearchRequest(
userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.AdminFilter,
[]string{ls.AttributeName},
@ -230,9 +229,9 @@ func (ls *Source) SearchEntry(name, passwd string, directBind bool) (string, str
sr, err = l.Search(search)
if err != nil {
log.Error(4, "LDAP Admin Search failed unexpectedly! (%v)", err)
log.Error(4, "LDAP admin search failed: %v", err)
} else if len(sr.Entries) < 1 {
log.Error(4, "LDAP Admin Search failed")
log.Error(4, "LDAP admin search failed: 0 entries")
} else {
isAdmin = true
}

8
modules/base/tool.go

@ -22,10 +22,10 @@ import (
"github.com/Unknwon/com"
"github.com/Unknwon/i18n"
log "gopkg.in/clog.v1"
"github.com/gogits/chardet"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)
@ -52,17 +52,17 @@ func ShortSha(sha1 string) string {
func DetectEncoding(content []byte) (string, error) {
if utf8.Valid(content) {
log.Debug("Detected encoding: utf-8 (fast)")
log.Trace("Detected encoding: utf-8 (fast)")
return "UTF-8", nil
}
result, err := chardet.NewTextDetector().DetectBest(content)
if result.Charset != "UTF-8" && len(setting.Repository.AnsiCharset) > 0 {
log.Debug("Using default AnsiCharset: %s", setting.Repository.AnsiCharset)
log.Trace("Using default AnsiCharset: %s", setting.Repository.AnsiCharset)
return setting.Repository.AnsiCharset, err
}
log.Debug("Detected encoding: %s", result.Charset)
log.Trace("Detected encoding: %s", result.Charset)
return result.Charset, err
}

4
modules/bindata/bindata.go

File diff suppressed because one or more lines are too long

2
modules/context/api.go

@ -9,10 +9,10 @@ import (
"strings"
"github.com/Unknwon/paginater"
log "gopkg.in/clog.v1"
"gopkg.in/macaron.v1"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)

8
modules/context/context.go

@ -16,12 +16,12 @@ import (
"github.com/go-macaron/csrf"
"github.com/go-macaron/i18n"
"github.com/go-macaron/session"
log "gopkg.in/clog.v1"
"gopkg.in/macaron.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)
@ -73,7 +73,7 @@ func (ctx *Context) HasValue(name string) bool {
// HTML calls Context.HTML and converts template name to string.
func (ctx *Context) HTML(status int, name base.TplName) {
log.Debug("Template: %s", name)
log.Trace("Template: %s", name)
ctx.Context.HTML(status, string(name))
}
@ -191,8 +191,8 @@ func Contexter() macaron.Handler {
ctx.Data["CsrfToken"] = x.GetToken()
ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`)
log.Debug("Session ID: %s", sess.ID())
log.Debug("CSRF Token: %v", ctx.Data["CsrfToken"])
log.Trace("Session ID: %s", sess.ID())
log.Trace("CSRF Token: %v", ctx.Data["CsrfToken"])
ctx.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton
ctx.Data["ShowFooterBranding"] = setting.ShowFooterBranding

4
modules/context/repo.go

@ -11,13 +11,13 @@ import (
"strings"
"github.com/Unknwon/com"
log "gopkg.in/clog.v1"
"gopkg.in/editorconfig/editorconfig-core-go.v1"
"gopkg.in/macaron.v1"
"github.com/gogits/git-module"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)
@ -267,7 +267,7 @@ func RepoAssignment(args ...bool) macaron.Handler {
// repo is bare and display enable
if ctx.Repo.Repository.IsBare {
log.Debug("Bare repository: %s", ctx.Repo.RepoLink)
log.Trace("Bare repository: %s", ctx.Repo.RepoLink)
// NOTE: to prevent templating error
ctx.Data["BranchName"] = ""
if displayBare {

3
modules/cron/cron.go

@ -7,10 +7,11 @@ package cron
import (
"time"
log "gopkg.in/clog.v1"
"github.com/gogits/cron"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)

104
modules/log/conn.go

@ -1,104 +0,0 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package log
import (
"encoding/json"
"io"
"log"
"net"
)
// ConnWriter implements LoggerInterface.
// it writes messages in keep-live tcp connection.
type ConnWriter struct {
lg *log.Logger
innerWriter io.WriteCloser
ReconnectOnMsg bool `json:"reconnectOnMsg"`
Reconnect bool `json:"reconnect"`
Net string `json:"net"`
Addr string `json:"addr"`
Level int `json:"level"`
}
// create new ConnWrite returning as LoggerInterface.
func NewConn() LoggerInterface {
conn := new(ConnWriter)
conn.Level = TRACE
return conn
}
// init connection writer with json config.
// json config only need key "level".
func (cw *ConnWriter) Init(jsonconfig string) error {
return json.Unmarshal([]byte(jsonconfig), cw)
}
// write message in connection.
// if connection is down, try to re-connect.
func (cw *ConnWriter) WriteMsg(msg string, skip, level int) error {
if cw.Level > level {
return nil
}
if cw.neddedConnectOnMsg() {
if err := cw.connect(); err != nil {
return err
}
}
if cw.ReconnectOnMsg {
defer cw.innerWriter.Close()
}
cw.lg.Println(msg)
return nil
}
func (_ *ConnWriter) Flush() {
}
// destroy connection writer and close tcp listener.
func (cw *ConnWriter) Destroy() {
if cw.innerWriter == nil {
return
}
cw.innerWriter.Close()
}
func (cw *ConnWriter) connect() error {
if cw.innerWriter != nil {
cw.innerWriter.Close()
cw.innerWriter = nil
}
conn, err := net.Dial(cw.Net, cw.Addr)
if err != nil {
return err
}
if tcpConn, ok := conn.(*net.TCPConn); ok {
tcpConn.SetKeepAlive(true)
}
cw.innerWriter = conn
cw.lg = log.New(conn, "", log.Ldate|log.Ltime)
return nil
}
func (cw *ConnWriter) neddedConnectOnMsg() bool {
if cw.Reconnect {
cw.Reconnect = false
return true
}
if cw.innerWriter == nil {
return true
}
return cw.ReconnectOnMsg
}
func init() {
Register("conn", NewConn)
}

73
modules/log/console.go

@ -1,73 +0,0 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package log
import (
"encoding/json"
"log"
"os"
"runtime"
)
type Brush func(string) string
func NewBrush(color string) Brush {
pre := "\033["
reset := "\033[0m"
return func(text string) string {
return pre + color + "m" + text + reset
}
}
var colors = []Brush{
NewBrush("1;36"), // Trace cyan
NewBrush("1;34"), // Debug blue
NewBrush("1;32"), // Info green
NewBrush("1;33"), // Warn yellow
NewBrush("1;31"), // Error red
NewBrush("1;35"), // Critical purple
NewBrush("1;31"), // Fatal red
}
// ConsoleWriter implements LoggerInterface and writes messages to terminal.
type ConsoleWriter struct {
lg *log.Logger
Level int `json:"level"`
}
// create ConsoleWriter returning as LoggerInterface.
func NewConsole() LoggerInterface {
return &ConsoleWriter{
lg: log.New(os.Stdout, "", log.Ldate|log.Ltime),
Level: TRACE,
}
}
func (cw *ConsoleWriter) Init(config string) error {
return json.Unmarshal([]byte(config), cw)
}
func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error {
if cw.Level > level {
return nil
}
if runtime.GOOS == "windows" {
cw.lg.Println(msg)
} else {
cw.lg.Println(colors[level](msg))
}
return nil
}
func (_ *ConsoleWriter) Flush() {
}
func (_ *ConsoleWriter) Destroy() {
}
func init() {
Register("console", NewConsole)
}

243
modules/log/file.go

@ -1,243 +0,0 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package log
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
// FileLogWriter implements LoggerInterface.
// It writes messages by lines limit, file size limit, or time frequency.
type FileLogWriter struct {
*log.Logger
mw *MuxWriter
// The opened file
Filename string `json:"filename"`
Maxlines int `json:"maxlines"`
maxlines_curlines int
// Rotate at size
Maxsize int `json:"maxsize"`
maxsize_cursize int
// Rotate daily
Daily bool `json:"daily"`
Maxdays int64 `json:"maxdays"`
daily_opendate int
Rotate bool `json:"rotate"`
startLock sync.Mutex // Only one log can write to the file
Level int `json:"level"`
}
// an *os.File writer with locker.
type MuxWriter struct {
sync.Mutex
fd *os.File
}
// write to os.File.
func (l *MuxWriter) Write(b []byte) (int, error) {
l.Lock()
defer l.Unlock()
return l.fd.Write(b)
}
// set os.File in writer.
func (l *MuxWriter) SetFd(fd *os.File) {
if l.fd != nil {
l.fd.Close()
}
l.fd = fd
}
// create a FileLogWriter returning as LoggerInterface.
func NewFileWriter() LoggerInterface {
w := &FileLogWriter{
Filename: "",
Maxlines: 1000000,
Maxsize: 1 << 28, //256 MB
Daily: true,
Maxdays: 7,
Rotate: true,
Level: TRACE,
}
// use MuxWriter instead direct use os.File for lock write when rotate
w.mw = new(MuxWriter)
// set MuxWriter as Logger's io.Writer
w.Logger = log.New(w.mw, "", log.Ldate|log.Ltime)
return w
}
// Init file logger with json config.
// config like:
// {
// "filename":"log/gogs.log",
// "maxlines":10000,
// "maxsize":1<<30,
// "daily":true,
// "maxdays":15,
// "rotate":true
// }
func (w *FileLogWriter) Init(config string) error {
if err := json.Unmarshal([]byte(config), w); err != nil {
return err
}
if len(w.Filename) == 0 {
return errors.New("config must have filename")
}
return w.StartLogger()
}
// start file logger. create log file and set to locker-inside file writer.
func (w *FileLogWriter) StartLogger() error {
fd, err := w.createLogFile()
if err != nil {
return err
}
w.mw.SetFd(fd)
if err = w.initFd(); err != nil {
return err
}
return nil
}
func (w *FileLogWriter) docheck(size int) {
w.startLock.Lock()
defer w.startLock.Unlock()
if w.Rotate && ((w.Maxlines > 0 && w.maxlines_curlines >= w.Maxlines) ||
(w.Maxsize > 0 && w.maxsize_cursize >= w.Maxsize) ||
(w.Daily && time.Now().Day() != w.daily_opendate)) {
if err := w.DoRotate(); err != nil {
fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.Filename, err)
return
}
}
w.maxlines_curlines++
w.maxsize_cursize += size
}
// write logger message into file.
func (w *FileLogWriter) WriteMsg(msg string, skip, level int) error {
if level < w.Level {
return nil
}
n := 24 + len(msg) // 24 stand for the length "2013/06/23 21:00:22 [T] "
w.docheck(n)
w.Logger.Println(msg)
return nil
}
func (w *FileLogWriter) createLogFile() (*os.File, error) {
// Open the log file
return os.OpenFile(w.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
}
func (w *FileLogWriter) initFd() error {
fd := w.mw.fd
finfo, err := fd.Stat()
if err != nil {
return fmt.Errorf("get stat: %s\n", err)
}
w.maxsize_cursize = int(finfo.Size())
w.daily_opendate = time.Now().Day()
if finfo.Size() > 0 {
content, err := ioutil.ReadFile(w.Filename)
if err != nil {
return err
}
w.maxlines_curlines = len(strings.Split(string(content), "\n"))
} else {
w.maxlines_curlines = 0
}
return nil
}
// DoRotate means it need to write file in new file.
// new file name like xx.log.2013-01-01.2
func (w *FileLogWriter) DoRotate() error {
_, err := os.Lstat(w.Filename)
if err == nil { // file exists
// Find the next available number
num := 1
fname := ""
for ; err == nil && num <= 999; num++ {
fname = w.Filename + fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num)
_, err = os.Lstat(fname)
}
// return error if the last file checked still existed
if err == nil {
return fmt.Errorf("rotate: cannot find free log number to rename %s\n", w.Filename)
}
// block Logger's io.Writer
w.mw.Lock()
defer w.mw.Unlock()
fd := w.mw.fd
fd.Close()
// close fd before rename
// Rename the file to its newfound home
if err = os.Rename(w.Filename, fname); err != nil {
return fmt.Errorf("Rotate: %s\n", err)
}
// re-start logger
if err = w.StartLogger(); err != nil {
return fmt.Errorf("Rotate StartLogger: %s\n", err)
}
go w.deleteOldLog()
}
return nil
}
func (w *FileLogWriter) deleteOldLog() {
dir := filepath.Dir(w.Filename)
filepath.Walk(dir, func(path string, info os.FileInfo, err error) (returnErr error) {
defer func() {
if r := recover(); r != nil {
returnErr = fmt.Errorf("Unable to delete old log '%s', error: %+v", path, r)
}
}()
if !info.IsDir() && info.ModTime().Unix() < (time.Now().Unix()-60*60*24*w.Maxdays) {
if strings.HasPrefix(filepath.Base(path), filepath.Base(w.Filename)) {
os.Remove(path)
}
}
return returnErr
})
}
// destroy file logger, close file writer.
func (w *FileLogWriter) Destroy() {
w.mw.fd.Close()
}
// flush file logger.
// there are no buffering messages in file logger in memory.
// flush file means sync file from disk.
func (w *FileLogWriter) Flush() {
w.mw.fd.Sync()
}
func init() {
Register("file", NewFileWriter)
}

312
modules/log/log.go

@ -1,312 +0,0 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package log
import (
"fmt"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"sync"
)
var (
loggers []*Logger
GitLogger *Logger
)
func NewLogger(bufLen int64, mode, config string) {
logger := newLogger(bufLen)
isExist := false
for i, l := range loggers {
if l.adapter == mode {
isExist = true
loggers[i] = logger
}
}
if !isExist {
loggers = append(loggers, logger)
}
if err := logger.SetLogger(mode, config); err != nil {
Fatal(2, "Fail to set logger (%s): %v", mode, err)
}
}
// FIXME: use same log level as other loggers.
func NewGitLogger(logPath string) {
os.MkdirAll(path.Dir(logPath), os.ModePerm)
GitLogger = newLogger(0)
GitLogger.SetLogger("file", fmt.Sprintf(`{"level":0,"filename":"%s","rotate":false}`, logPath))
}
func Trace(format string, v ...interface{}) {
for _, logger := range loggers {
logger.Trace(format, v...)
}
}
func Debug(format string, v ...interface{}) {
for _, logger := range loggers {
logger.Debug(format, v...)
}
}
func Info(format string, v ...interface{}) {
for _, logger := range loggers {
logger.Info(format, v...)
}
}
func Warn(format string, v ...interface{}) {
for _, logger := range loggers {
logger.Warn(format, v...)
}
}
func Error(skip int, format string, v ...interface{}) {
for _, logger := range loggers {
logger.Error(skip, format, v...)
}
}
func Critical(skip int, format string, v ...interface{}) {
for _, logger := range loggers {
logger.Critical(skip, format, v...)
}
}
func Fatal(skip int, format string, v ...interface{}) {
Error(skip, format, v...)
for _, l := range loggers {
l.Close()
}
os.Exit(1)
}
func Close() {
for _, l := range loggers {
l.Close()
}
}
// .___ __ _____
// | | _____/ |_ ____________/ ____\____ ____ ____
// | |/ \ __\/ __ \_ __ \ __\\__ \ _/ ___\/ __ \
// | | | \ | \ ___/| | \/| | / __ \\ \__\ ___/
// |___|___| /__| \___ >__| |__| (____ /\___ >___ >
// \/ \/ \/ \/ \/
type LogLevel int
const (
TRACE = iota
DEBUG
INFO
WARN
ERROR
CRITICAL
FATAL
)
// LoggerInterface represents behaviors of a logger provider.
type LoggerInterface interface {
Init(config string) error
WriteMsg(msg string, skip, level int) error
Destroy()
Flush()
}
type loggerType func() LoggerInterface
var adapters = make(map[string]loggerType)
// Register registers given logger provider to adapters.
func Register(name string, log loggerType) {
if log == nil {
panic("log: register provider is nil")
}
if _, dup := adapters[name]; dup {
panic("log: register called twice for provider \"" + name + "\"")
}
adapters[name] = log
}
type logMsg struct {
skip, level int
msg string
}
// Logger is default logger in beego application.
// it can contain several providers and log message into all providers.
type Logger struct {
adapter string
lock sync.Mutex
level int
msg chan *logMsg
outputs map[string]LoggerInterface
quit chan bool
}
// newLogger initializes and returns a new logger.
func newLogger(buffer int64) *Logger {
l := &Logger{
msg: make(chan *logMsg, buffer),
outputs: make(map[string]LoggerInterface),
quit: make(chan bool),
}
go l.StartLogger()
return l
}
// SetLogger sets new logger instance with given logger adapter and config.
func (l *Logger) SetLogger(adapter string, config string) error {
l.lock.Lock()
defer l.lock.Unlock()
if log, ok := adapters[adapter]; ok {
lg := log()
if err := lg.Init(config); err != nil {
return err
}
l.outputs[adapter] = lg
l.adapter = adapter
} else {
panic("log: unknown adapter \"" + adapter + "\" (forgotten register?)")
}
return nil
}
// DelLogger removes a logger adapter instance.
func (l *Logger) DelLogger(adapter string) error {
l.lock.Lock()
defer l.lock.Unlock()
if lg, ok := l.outputs[adapter]; ok {
lg.Destroy()
delete(l.outputs, adapter)
} else {
panic("log: unknown adapter \"" + adapter + "\" (forgotten register?)")
}
return nil
}
func (l *Logger) writerMsg(skip, level int, msg string) error {
if l.level > level {
return nil
}
lm := &logMsg{
skip: skip,
level: level,
}
// Only error information needs locate position for debugging.
if lm.level >= ERROR {
pc, file, line, ok := runtime.Caller(skip)
if ok {
// Get caller function name.
fn := runtime.FuncForPC(pc)
var fnName string
if fn == nil {
fnName = "?()"
} else {
fnName = strings.TrimLeft(filepath.Ext(fn.Name()), ".") + "()"
}
fileName := file
if len(fileName) > 20 {
fileName = "..." + fileName[len(fileName)-20:]
}
lm.msg = fmt.Sprintf("[%s:%d %s] %s", fileName, line, fnName, msg)
} else {
lm.msg = msg
}
} else {
lm.msg = msg
}
l.msg <- lm
return nil
}
// StartLogger starts logger chan reading.
func (l *Logger) StartLogger() {
for {
select {
case bm := <-l.msg:
for _, l := range l.outputs {
if err := l.WriteMsg(bm.msg, bm.skip, bm.level); err != nil {
fmt.Println("ERROR, unable to WriteMsg:", err)
}
}
case <-l.quit:
return
}
}
}
// Flush flushs all chan data.
func (l *Logger) Flush() {
for _, l := range l.outputs {
l.Flush()
}
}
// Close closes logger, flush all chan data and destroy all adapter instances.
func (l *Logger) Close() {
l.quit <- true
for {
if len(l.msg) > 0 {
bm := <-l.msg
for _, l := range l.outputs {
if err := l.WriteMsg(bm.msg, bm.skip, bm.level); err != nil {
fmt.Println("ERROR, unable to WriteMsg:", err)
}
}
} else {
break
}
}
for _, l := range l.outputs {
l.Flush()
l.Destroy()
}
}
func (l *Logger) Trace(format string, v ...interface{}) {
msg := fmt.Sprintf("[T] "+format, v...)
l.writerMsg(0, TRACE, msg)
}
func (l *Logger) Debug(format string, v ...interface{}) {
msg := fmt.Sprintf("[D] "+format, v...)
l.writerMsg(0, DEBUG, msg)
}
func (l *Logger) Info(format string, v ...interface{}) {
msg := fmt.Sprintf("[I] "+format, v...)
l.writerMsg(0, INFO, msg)
}
func (l *Logger) Warn(format string, v ...interface{}) {
msg := fmt.Sprintf("[W] "+format, v...)
l.writerMsg(0, WARN, msg)
}
func (l *Logger) Error(skip int, format string, v ...interface{}) {
msg := fmt.Sprintf("[E] "+format, v...)
l.writerMsg(skip, ERROR, msg)
}
func (l *Logger) Critical(skip int, format string, v ...interface{}) {
msg := fmt.Sprintf("[C] "+format, v...)
l.writerMsg(skip, CRITICAL, msg)
}
func (l *Logger) Fatal(skip int, format string, v ...interface{}) {
msg := fmt.Sprintf("[F] "+format, v...)
l.writerMsg(skip, FATAL, msg)
l.Close()
os.Exit(1)
}

87
modules/log/smtp.go

@ -1,87 +0,0 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package log
import (
"encoding/json"
"fmt"
"net/smtp"
"strings"
"time"
)
const (
subjectPhrase = "Diagnostic message from server"
)
// smtpWriter implements LoggerInterface and is used to send emails via given SMTP-server.
type SmtpWriter struct {
Username string `json:"Username"`
Password string `json:"password"`
Host string `json:"Host"`
Subject string `json:"subject"`
RecipientAddresses []string `json:"sendTos"`
Level int `json:"level"`
}
// create smtp writer.
func NewSmtpWriter() LoggerInterface {
return &SmtpWriter{Level: TRACE}
}
// init smtp writer with json config.
// config like:
// {
// "Username":"example@gmail.com",
// "password:"password",
// "host":"smtp.gmail.com:465",
// "subject":"email title",
// "sendTos":["email1","email2"],
// "level":LevelError
// }
func (sw *SmtpWriter) Init(jsonconfig string) error {
return json.Unmarshal([]byte(jsonconfig), sw)
}
// write message in smtp writer.
// it will send an email with subject and only this message.
func (s *SmtpWriter) WriteMsg(msg string, skip, level int) error {
if level < s.Level {
return nil
}
hp := strings.Split(s.Host, ":")
// Set up authentication information.
auth := smtp.PlainAuth(
"",
s.Username,
s.Password,
hp[0],
)
// Connect to the server, authenticate, set the sender and recipient,
// and send the email all in one step.
content_type := "Content-Type: text/plain" + "; charset=UTF-8"
mailmsg := []byte("To: " + strings.Join(s.RecipientAddresses, ";") + "\r\nFrom: " + s.Username + "<" + s.Username +
">\r\nSubject: " + s.Subject + "\r\n" + content_type + "\r\n\r\n" + fmt.Sprintf(".%s", time.Now().Format("2006-01-02 15:04:05")) + msg)
return smtp.SendMail(
s.Host,
auth,
s.Username,
s.RecipientAddresses,
mailmsg,
)
}
func (_ *SmtpWriter) Flush() {
}
func (_ *SmtpWriter) Destroy() {
}
func init() {
Register("smtp", NewSmtpWriter)
}

2
modules/mailer/mail.go

@ -8,11 +8,11 @@ import (
"fmt"
"html/template"
log "gopkg.in/clog.v1"
"gopkg.in/gomail.v2"
"gopkg.in/macaron.v1"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/markdown"
"github.com/gogits/gogs/modules/setting"
)

2
modules/mailer/mailer.go

@ -15,9 +15,9 @@ import (
"time"
"github.com/jaytaylor/html2text"
log "gopkg.in/clog.v1"
"gopkg.in/gomail.v2"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)

2
modules/process/manager.go

@ -11,7 +11,7 @@ import (
"os/exec"
"time"
"github.com/gogits/gogs/modules/log"
log "gopkg.in/clog.v1"
)
var (

117
modules/setting/setting.go

@ -5,7 +5,6 @@
package setting
import (
"fmt"
"net/mail"
"net/url"
"os"
@ -22,12 +21,12 @@ import (
_ "github.com/go-macaron/cache/redis"
"github.com/go-macaron/session"
_ "github.com/go-macaron/session/redis"
log "gopkg.in/clog.v1"
"gopkg.in/ini.v1"
"github.com/gogits/go-libravatar"
"github.com/gogits/gogs/modules/bindata"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/user"
)
@ -180,7 +179,7 @@ var (
// Log settings
LogRootPath string
LogModes []string
LogConfigs []string
LogConfigs []interface{}
// Attachment settings
AttachmentPath string
@ -290,11 +289,11 @@ func execPath() (string, error) {
func init() {
IsWindows = runtime.GOOS == "windows"
log.NewLogger(0, "console", `{"level": 0}`)
log.New(log.CONSOLE, log.ConsoleConfig{})
var err error
if AppPath, err = execPath(); err != nil {
log.Fatal(4, "fail to get app path: %v\n", err)
log.Fatal(4, "Fail to get app path: %v\n", err)
}
// Note: we don't use path.Dir here because it does not handle case
@ -617,82 +616,78 @@ func newService() {
Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
}
var logLevels = map[string]string{
"Trace": "0",
"Debug": "1",
"Info": "2",
"Warn": "3",
"Error": "4",
"Critical": "5",
}
func newLogService() {
log.Info("%s %s", AppName, AppVer)
if len(BuildTime) > 0 {
log.Info("Build Time: %s", BuildTime)
log.Info("Build Git Hash: %s", BuildGitHash)
}
// Because we always create a console logger as primary logger before all settings are loaded,
// thus if user doesn't set console logger, we should remove it after other loggers are created.
hasConsole := false
// Get and check log mode.
LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
LogConfigs = make([]string, len(LogModes))
LogConfigs = make([]interface{}, len(LogModes))
for i, mode := range LogModes {
mode = strings.TrimSpace(mode)
mode = strings.ToLower(strings.TrimSpace(mode))
sec, err := Cfg.GetSection("log." + mode)
if err != nil {
log.Fatal(4, "Unknown log mode: %s", mode)
log.Fatal(4, "Unknown logger mode: %s", mode)
}
validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
// Log level.
levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
validLevels)
level, ok := logLevels[levelName]
if !ok {
log.Fatal(4, "Unknown log level: %s", levelName)
validLevels := []string{"trace", "info", "warn", "error", "fatal"}
levelName := Cfg.Section("log." + mode).Key("LEVEL").Validate(func(v string) string {
v = strings.ToLower(v)
if com.IsSliceContainsStr(validLevels, v) {
return v
}
return "trace"
})
level := map[string]log.LEVEL{
"trace": log.TRACE,
"info": log.INFO,
"warn": log.WARN,
"error": log.ERROR,
"fatal": log.FATAL,
}[levelName]
// Generate log configuration.
switch mode {
case "console":
LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
hasConsole = true
LogConfigs[i] = log.ConsoleConfig{
Level: level,
BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
}
case "file":
logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
logPath := path.Join(LogRootPath, "gogs.log")
if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
panic(err.Error())
}
LogConfigs[i] = fmt.Sprintf(
`{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
logPath,
sec.Key("LOG_ROTATE").MustBool(true),
sec.Key("MAX_LINES").MustInt(1000000),
1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
sec.Key("DAILY_ROTATE").MustBool(true),
sec.Key("MAX_DAYS").MustInt(7))
case "conn":
LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
sec.Key("RECONNECT_ON_MSG").MustBool(),
sec.Key("RECONNECT").MustBool(),
sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
sec.Key("ADDR").MustString(":7020"))
case "smtp":
LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":["%s"],"subject":"%s"}`, level,
sec.Key("USER").MustString("example@example.com"),
sec.Key("PASSWD").MustString("******"),
sec.Key("HOST").MustString("127.0.0.1:25"),
strings.Replace(sec.Key("RECEIVERS").MustString(""), ",", `","`, -1),
sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
case "database":
LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
sec.Key("DRIVER").String(),
sec.Key("CONN").String())
}
log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
log.Fatal(4, "Fail to create log directory '%s': %v", path.Dir(logPath), err)
}
LogConfigs[i] = log.FileConfig{
Level: level,
BufferSize: Cfg.Section("log").Key("BUFFER_LEN").MustInt64(100),
Filename: logPath,
FileRotationConfig: log.FileRotationConfig{
Rotate: sec.Key("LOG_ROTATE").MustBool(true),
Daily: sec.Key("DAILY_ROTATE").MustBool(true),
MaxSize: 1 << uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
MaxLines: sec.Key("MAX_LINES").MustInt64(1000000),
MaxDays: sec.Key("MAX_DAYS").MustInt64(7),
},
}
}
log.New(log.MODE(mode), LogConfigs[i])
log.Trace("Log Mode: %s (%s)", strings.Title(mode), strings.Title(levelName))
}
// Make sure everyone gets version info printed.
log.Info("%s %s", AppName, AppVer)
if !hasConsole {
log.Delete(log.CONSOLE)
}
}

2
modules/ssh/ssh.go

@ -16,9 +16,9 @@ import (
"github.com/Unknwon/com"
"golang.org/x/crypto/ssh"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)

2
modules/template/template.go

@ -17,11 +17,11 @@ import (
"golang.org/x/net/html/charset"
"golang.org/x/text/transform"
log "gopkg.in/clog.v1"
"gopkg.in/editorconfig/editorconfig-core-go.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/markdown"
"github.com/gogits/gogs/modules/setting"
)

8
routers/admin/admin.go

@ -5,6 +5,7 @@
package admin
import (
"encoding/json"
"fmt"
"runtime"
"strings"
@ -232,7 +233,12 @@ func Config(ctx *context.Context) {
}
loggers := make([]*logger, len(setting.LogModes))
for i := range setting.LogModes {
loggers[i] = &logger{setting.LogModes[i], setting.LogConfigs[i]}
loggers[i] = &logger{
Mode: strings.Title(setting.LogModes[i]),
}
result, _ := json.Marshal(setting.LogConfigs[i])
loggers[i].Config = string(result)
}
ctx.Data["Loggers"] = loggers

2
routers/admin/auths.go

@ -9,13 +9,13 @@ import (
"github.com/Unknwon/com"
"github.com/go-xorm/core"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/auth/ldap"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)

2
routers/admin/notice.go

@ -7,11 +7,11 @@ package admin
import (
"github.com/Unknwon/com"
"github.com/Unknwon/paginater"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)

3
routers/admin/repos.go

@ -5,10 +5,11 @@
package admin
import (
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/routers"
)

2
routers/admin/users.go

@ -8,12 +8,12 @@ import (
"strings"
"github.com/Unknwon/com"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/mailer"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/routers"

3
routers/api/v1/admin/user.go

@ -5,11 +5,12 @@
package admin
import (
log "gopkg.in/clog.v1"
api "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/mailer"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/routers/api/v1/user"

3
routers/api/v1/repo/repo.go

@ -7,12 +7,13 @@ package repo
import (
"path"
log "gopkg.in/clog.v1"
api "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/routers/api/v1/convert"
)

3
routers/install.go

@ -14,6 +14,7 @@ import (
"github.com/Unknwon/com"
"github.com/go-xorm/xorm"
log "gopkg.in/clog.v1"
"gopkg.in/ini.v1"
"gopkg.in/macaron.v1"
@ -24,7 +25,6 @@ import (
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/cron"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/mailer"
"github.com/gogits/gogs/modules/markdown"
"github.com/gogits/gogs/modules/setting"
@ -76,7 +76,6 @@ func GlobalInit() {
models.InitSyncMirrors()
models.InitDeliverHooks()
models.InitTestPullRequests()
log.NewGitLogger(path.Join(setting.LogRootPath, "http.log"))
}
if models.EnableSQLite3 {
log.Info("SQLite3 Supported")

2
routers/org/members.go

@ -6,11 +6,11 @@ package org
import (
"github.com/Unknwon/com"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)

3
routers/org/org.go

@ -5,11 +5,12 @@
package org
import (
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)

3
routers/org/setting.go

@ -7,11 +7,12 @@ package org
import (
"strings"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/routers/user"
)

2
routers/org/teams.go

@ -8,12 +8,12 @@ import (
"path"
"github.com/Unknwon/com"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
)
const (

3
routers/repo/branch.go

@ -5,11 +5,12 @@
package repo
import (
log "gopkg.in/clog.v1"
"github.com/gogits/git-module"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
)
const (

3
routers/repo/editor.go

@ -11,12 +11,13 @@ import (
"path"
"strings"
log "gopkg.in/clog.v1"
"github.com/gogits/git-module"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/modules/template"
)

19
routers/repo/http.go

@ -20,12 +20,13 @@ import (
"strings"
"time"
log "gopkg.in/clog.v1"
git "github.com/gogits/git-module"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)
@ -315,7 +316,7 @@ func gitCommand(dir string, args ...string) []byte {
cmd.Dir = dir
out, err := cmd.Output()
if err != nil {
log.GitLogger.Error(4, fmt.Sprintf("%v - %s", err, out))
log.Error(4, fmt.Sprintf("Git: %v - %s", err, out))
}
return out
}
@ -376,7 +377,7 @@ func serviceRPC(h serviceHandler, service string) {
if h.r.Header.Get("Content-Encoding") == "gzip" {
reqBody, err = gzip.NewReader(reqBody)
if err != nil {
log.GitLogger.Error(2, "fail to create gzip reader: %v", err)
log.Error(2, "Git: fail to create gzip reader: %v", err)
h.w.WriteHeader(http.StatusInternalServerError)
return
}
@ -385,7 +386,7 @@ func serviceRPC(h serviceHandler, service string) {
if h.cfg.OnSucceed != nil {
tmpfile, err := ioutil.TempFile("", "gogs")
if err != nil {
log.GitLogger.Error(2, "fail to create temporary file: %v", err)
log.Error(2, "Git: fail to create temporary file: %v", err)
h.w.WriteHeader(http.StatusInternalServerError)
return
}
@ -393,7 +394,7 @@ func serviceRPC(h serviceHandler, service string) {
_, err = io.Copy(tmpfile, reqBody)
if err != nil {
log.GitLogger.Error(2, "fail to save request body: %v", err)
log.Error(2, "Git: fail to save request body: %v", err)
h.w.WriteHeader(http.StatusInternalServerError)
return
}
@ -402,7 +403,7 @@ func serviceRPC(h serviceHandler, service string) {
tmpFilename = tmpfile.Name()
tmpfile, err = os.Open(tmpFilename)
if err != nil {
log.GitLogger.Error(2, "fail to open temporary file: %v", err)
log.Error(2, "Git: fail to open temporary file: %v", err)
h.w.WriteHeader(http.StatusInternalServerError)
return
}
@ -420,7 +421,7 @@ func serviceRPC(h serviceHandler, service string) {
cmd.Stderr = &stderr
cmd.Stdin = br
if err := cmd.Run(); err != nil {
log.GitLogger.Error(2, "fail to serve RPC(%s): %v - %s", service, err, stderr)
log.Error(2, "Git: fail to serve RPC '%s': %v - %s", service, err, stderr)
h.w.WriteHeader(http.StatusInternalServerError)
return
}
@ -428,7 +429,7 @@ func serviceRPC(h serviceHandler, service string) {
if h.cfg.OnSucceed != nil {
input, err := os.Open(tmpFilename)
if err != nil {
log.GitLogger.Error(2, "fail to open temporary file: %v", err)
log.Error(2, "Git: fail to open temporary file: %v", err)
h.w.WriteHeader(http.StatusInternalServerError)
return
}
@ -545,7 +546,7 @@ func HTTPBackend(ctx *context.Context, cfg *serviceConfig) http.HandlerFunc {
file := strings.Replace(r.URL.Path, m[1]+"/", "", 1)
dir, err := getGitRepoPath(m[1])
if err != nil {
log.GitLogger.Error(4, err.Error())
log.Error(4, "Git: getGitRepoPath: %v", err)
ctx.Handle(http.StatusNotFound, "HTTPBackend", err)
return
}

2
routers/repo/issue.go

@ -16,12 +16,12 @@ import (
"github.com/Unknwon/com"
"github.com/Unknwon/paginater"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/markdown"
"github.com/gogits/gogs/modules/setting"
)

2
routers/repo/pull.go

@ -10,6 +10,7 @@ import (
"strings"
"github.com/Unknwon/com"
log "gopkg.in/clog.v1"
"github.com/gogits/git-module"
@ -17,7 +18,6 @@ import (
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)

3
routers/repo/release.go

@ -7,11 +7,12 @@ package repo
import (
"fmt"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/markdown"
)

2
routers/repo/repo.go

@ -11,6 +11,7 @@ import (
"strings"
"github.com/Unknwon/com"
log "gopkg.in/clog.v1"
"github.com/gogits/git-module"
@ -18,7 +19,6 @@ import (
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)

3
routers/repo/setting.go

@ -8,13 +8,14 @@ import (
"strings"
"time"
log "gopkg.in/clog.v1"
"github.com/gogits/git-module"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/mailer"
"github.com/gogits/gogs/modules/setting"
)

2
routers/repo/view.go

@ -13,13 +13,13 @@ import (
"strings"
"github.com/Unknwon/paginater"
log "gopkg.in/clog.v1"
"github.com/gogits/git-module"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/markdown"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/modules/template"

2
routers/user/auth.go

@ -9,12 +9,12 @@ import (
"net/url"
"github.com/go-macaron/captcha"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/mailer"
"github.com/gogits/gogs/modules/setting"
)

2
routers/user/setting.go

@ -11,12 +11,12 @@ import (
"strings"
"github.com/Unknwon/com"
log "gopkg.in/clog.v1"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/mailer"
"github.com/gogits/gogs/modules/setting"
)

2
templates/.VERSION

@ -1 +1 @@
0.9.138.0209
0.9.139.0209
Loading…
Cancel
Save