Skip to content

Commit

Permalink
Change logging flags
Browse files Browse the repository at this point in the history
  • Loading branch information
nim4 committed Apr 1, 2017
1 parent fd733fc commit b52a0a0
Show file tree
Hide file tree
Showing 10 changed files with 89 additions and 46 deletions.
7 changes: 5 additions & 2 deletions conf/dbshield.yml
Expand Up @@ -37,8 +37,11 @@ SyncInterval: 5s
#############################
### HTTP Service ###
#############################
# Run http service(default: on)
http: on
# Run http interface(default: yes)
http: yes

# Serve https (default: yes)
httpSSL: yes

# IP address to listen on(default: 127.0.0.1)
httpIP: 127.0.0.1
Expand Down
2 changes: 2 additions & 0 deletions dbshield/config/config.go
Expand Up @@ -43,6 +43,7 @@ type Configurations struct {
TLSCertificate string

HTTP bool
HTTPSSL bool
HTTPAddr string
HTTPPassword string

Expand Down Expand Up @@ -201,6 +202,7 @@ func configHTTP() error {
if err != nil {
return err
}
Config.HTTPSSL = viper.GetBool("httpSSL")
Config.HTTPAddr = fmt.Sprintf("%s:%d", httpIP, httpPort)
}
return nil
Expand Down
6 changes: 5 additions & 1 deletion dbshield/dbshield.go
Expand Up @@ -111,7 +111,11 @@ func postConfig() (err error) {

func mainListner() error {
if config.Config.HTTP {
logger.Infof("Web interface on https://%s/", config.Config.HTTPAddr)
proto := "http"
if config.Config.HTTPSSL {
proto = "https"
}
logger.Infof("Web interface on %s://%s/", proto, config.Config.HTTPAddr)
go httpserver.Serve()
}
serverAddr, _ := net.ResolveTCPAddr("tcp", config.Config.TargetIP+":"+strconv.Itoa(int(config.Config.TargetPort)))
Expand Down
6 changes: 4 additions & 2 deletions dbshield/httpserver/server.go
Expand Up @@ -28,11 +28,13 @@ func serve() {
http.HandleFunc("/logout", logoutHandler)
}

//Serve HTTPS
//Serve HTTP
func Serve() error {
singleHTTP.Do(serve)
if config.Config.HTTPSSL {
return http.ListenAndServeTLS(config.Config.HTTPAddr, config.Config.TLSCertificate, config.Config.TLSPrivateKey, nil)
}
return http.ListenAndServe(config.Config.HTTPAddr, nil)
//return http.ListenAndServeTLS(config.Config.HTTPAddr, config.Config.TLSCertificate, config.Config.TLSPrivateKey, nil)
}

//mainHandler for html
Expand Down
5 changes: 5 additions & 0 deletions dbshield/httpserver/server_test.go
Expand Up @@ -47,6 +47,11 @@ func TestServe(t *testing.T) {
if err == nil {
t.Error("Expected error")
}
config.Config.HTTPSSL = true
err = Serve()
if err == nil {
t.Error("Expected error")
}
}

func TestMainHandler(t *testing.T) {
Expand Down
43 changes: 34 additions & 9 deletions dbshield/logger/log.go
@@ -1,22 +1,47 @@
package logger

import (
"fmt"
"log"
"os"
)

//Level of logging
var Level uint

const (
flagWarning = 0x1
flagInfo = 0x2
flagDebug = 0x4
)

var (
warn bool
info bool
debug bool
)

//Output of logging functions
var Output *os.File

//Init the log output and logging level
func Init(path string, level uint) error {
switch path {
case "stdout":
Output = os.Stdout
case "stderr":
Output = os.Stderr
default:
var err error
Output, err = os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
return fmt.Errorf("Error opening log file: %v", err)
}
}
log.SetOutput(Output)
warn = level&flagWarning == flagWarning
info = level&flagInfo == flagInfo
debug = level&flagDebug == flagDebug
return nil
}

func println(title string, msg ...interface{}) {
arg := append([]interface{}{title}, msg...)
log.Println(arg...)
Expand All @@ -28,42 +53,42 @@ func printFormat(format string, msg ...interface{}) {

//Debug level > 1 logging with "[DEBUG]" prefix
func Debug(msg ...interface{}) {
if Level&flagDebug == flagDebug {
if debug {
println("[DEBUG]", msg...)
}
}

//Debugf level > 1 format logging with "[DEBUG]" prefix
func Debugf(format string, msg ...interface{}) {
if Level&flagDebug == flagDebug {
if debug {
printFormat("[DEBUG] "+format, msg...)
}
}

//Info level > 0 logging with "[INFO]" prefix
func Info(msg ...interface{}) {
if Level&flagInfo == flagInfo {
if info {
println("[INFO] ", msg...)
}
}

//Infof level > 0 format logging with "[INFO]" prefix
func Infof(format string, msg ...interface{}) {
if Level&flagInfo == flagInfo {
if info {
printFormat("[INFO] "+format, msg...)
}
}

//Warning any level logging with "[WARN]" prefix
func Warning(msg ...interface{}) {
if Level&flagWarning == flagWarning {
if warn {
println("[WARN] ", msg...)
}
}

//Warningf any level format logging with "[WARN]" prefix
func Warningf(format string, msg ...interface{}) {
if Level&flagWarning == flagWarning {
if warn {
printFormat("[WARN] "+format, msg...)
}
}
25 changes: 22 additions & 3 deletions dbshield/logger/log_test.go
@@ -1,15 +1,16 @@
package logger_test

import (
"os"
"testing"

"github.com/nim4/DBShield/dbshield/logger"
)

func TestLogger(t *testing.T) {
logger.Init("stderr", 7)
format := "%s"
msg := "Test"
logger.Level = 7
logger.Debug(msg)
logger.Debugf(format, msg)
logger.Info(msg)
Expand All @@ -18,15 +19,33 @@ func TestLogger(t *testing.T) {
logger.Warningf(format, msg)
}

func TestInit(t *testing.T) {

err := logger.Init(os.TempDir(), 0)
if err == nil {
t.Error("Expected error")
}

err = logger.Init("stdout", 0)
if err != nil {
t.Error("Got error", err)
}

err = logger.Init("stderr", 7)
if err != nil {
t.Error("Got error", err)
}
}

func BenchmarkDebugf(b *testing.B) {
logger.Level = 7
logger.Init("stderr", 7)
for i := 0; i < b.N; i++ {
logger.Debugf("%s", "t")
}
}

func BenchmarkDebug(b *testing.B) {
logger.Level = 7
logger.Init("stderr", 7)
for i := 0; i < b.N; i++ {
logger.Debug("t")
}
Expand Down
17 changes: 3 additions & 14 deletions dbshield/utils.go
Expand Up @@ -3,7 +3,6 @@ package dbshield
import (
"encoding/binary"
"fmt"
"log"
"net"
"os"
"os/signal"
Expand Down Expand Up @@ -93,20 +92,10 @@ func signalHandler() {

//initLogging redirect log output to file/stdout/stderr
func initLogging() {
switch config.Config.LogPath {
case "stdout":
logger.Output = os.Stdout
case "stderr":
logger.Output = os.Stderr
default:
var err error
logger.Output, err = os.OpenFile(config.Config.LogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(fmt.Errorf("Error opening log file: %v", err))
}
err := logger.Init(config.Config.LogPath, config.Config.LogLevel)
if err != nil {
panic(err)
}
log.SetOutput(logger.Output)
logger.Level = config.Config.LogLevel
}

//maps database name to corresponding struct
Expand Down
14 changes: 2 additions & 12 deletions dbshield/utils_test.go
Expand Up @@ -39,16 +39,6 @@ func TestDbNameToStruct(t *testing.T) {
func TestInitLogging(t *testing.T) {
config.Config.LogPath = "stdout"
initLogging()
config.Config.LogPath = "stderr"
initLogging()

defer func() {
if r := recover(); r == nil {
t.Error("Expected panic")
}
}()
config.Config.LogPath = os.TempDir()
initLogging()
}

func TestHandleClient(t *testing.T) {
Expand Down Expand Up @@ -86,7 +76,7 @@ func TestCloseHandlers(t *testing.T) {
}

func TestGenerateDBMS(t *testing.T) {
config.Config.DB = 1
config.Config.DB = 0
v := generateDBMS()
if v == nil {
t.Error("Got nil")
Expand All @@ -110,7 +100,7 @@ func TestGenerateDBMS(t *testing.T) {
t.Error("Got nil")
}

config.Config.DB++
config.Config.DB = 100
v = generateDBMS()
if v != nil {
t.Error("Expected nil")
Expand Down
10 changes: 7 additions & 3 deletions main_test.go
Expand Up @@ -11,7 +11,6 @@ import (
func TestEveryThing(t *testing.T) {
usage(true)

//
os.Args = []string{os.Args[0], "-k", "-c", "conf/dbshield.yml"}
main()

Expand Down Expand Up @@ -41,11 +40,16 @@ func TestEveryThing(t *testing.T) {
t.Fatal(err)
}
path := os.TempDir() + "/tempconfig.yml"
dat = bytes.Replace(dat, []byte("dbDir: "), []byte("dbDir: "+path), 1)
dat = bytes.Replace(dat, []byte("logPath: "), []byte("logPath: "+os.TempDir()+" #"), 1)
err = ioutil.WriteFile(path, dat, 0600)
if err != nil {
t.Fatal(err)
}
os.Args = []string{os.Args[0], "-k", "-c", path}
os.Args = []string{os.Args[0], "-c", path}
defer func() {
if r := recover(); r == nil {
t.Error("Expected panic")
}
}()
main()
}

0 comments on commit b52a0a0

Please sign in to comment.