Skip to content

Commit

Permalink
windows: Add logging to the event log.
Browse files Browse the repository at this point in the history
  • Loading branch information
Jacob Marble committed Feb 23, 2016
1 parent 2734edf commit 9e41f0b
Show file tree
Hide file tree
Showing 10 changed files with 93 additions and 53 deletions.
9 changes: 0 additions & 9 deletions gcp-connector-util/common.go

This file was deleted.

2 changes: 1 addition & 1 deletion gcp-connector-util/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ func initConfigFile(context *cli.Context) {
if context.IsSet("proxy-name") {
proxyName = context.String("proxy-name")
} else {
proxyName = scanNonEmptyString("Proxy name for this GCP CUPS Connector:")
proxyName = scanNonEmptyString("Proxy name for this connector:")
}

var userClient *http.Client
Expand Down
32 changes: 31 additions & 1 deletion gcp-connector-util/main_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@
package main

import (
"fmt"
"log"
"os"

"github.com/codegangsta/cli"
"github.com/google/cups-connector/lib"
"golang.org/x/sys/windows/svc/eventlog"
)

var windowsCommands = []cli.Command{
Expand All @@ -24,19 +26,47 @@ var windowsCommands = []cli.Command{
Action: initConfigFile,
Flags: commonInitFlags,
},
cli.Command{
Name: "install-event-log",
Usage: "Installs registry entries for the event log",
Action: installEventLog,
},
cli.Command{
Name: "remove-event-log",
Usage: "Removes registry entries for the event log",
Action: removeEventLog,
},
}

func updateConfig(config *lib.Config, configMap map[string]interface{}) bool {
return commonUpdateConfig(config, configMap)
}

func installEventLog(c *cli.Context) {
err := eventlog.InstallAsEventCreate(lib.ConnectorName, eventlog.Error|eventlog.Warning|eventlog.Info)
if err != nil {
fmt.Printf("Failed to install event log registry entries: %s\n", err)
os.Exit(1)
}
fmt.Println("Event log registry entries installed successfully")
}

func removeEventLog(c *cli.Context) {
err := eventlog.Remove(lib.ConnectorName)
if err != nil {
fmt.Printf("Failed to remove event log registry entries: %s\n", err)
os.Exit(1)
}
fmt.Println("Event log registry entries removed successfully")
}

func main() {
// Suppress date/time prefix.
log.SetFlags(0)

app := cli.NewApp()
app.Name = "gcp-windows-connector-util"
app.Usage = "Google Cloud Print Windows Connector utility tools"
app.Usage = lib.ConnectorName + " for Windows utility tools"
app.Version = lib.BuildDate
app.Flags = []cli.Flag{
lib.ConfigFilenameFlag,
Expand Down
2 changes: 1 addition & 1 deletion gcp-cups-connector/gcp-cups-connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import (
func main() {
app := cli.NewApp()
app.Name = "gcp-cups-connector"
app.Usage = "Google Cloud Print CUPS Connector"
app.Usage = "Google Cloud Print Connector for CUPS"
app.Version = lib.BuildDate
app.Flags = []cli.Flag{
lib.ConfigFilenameFlag,
Expand Down
33 changes: 15 additions & 18 deletions gcp-windows-connector/gcp-windows-connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"github.com/google/cups-connector/manager"
"github.com/google/cups-connector/winspool"
"github.com/google/cups-connector/xmpp"
"golang.org/x/sys/windows/svc"
)

// TODO: Windows Service.
Expand All @@ -30,15 +31,8 @@ import (
func main() {
app := cli.NewApp()
app.Name = "gcp-windows-connector"
app.Usage = "Google Cloud Print Windows Connector"
app.Usage = "Google Cloud Print Connector for Windows"
app.Version = lib.BuildDate
app.Flags = []cli.Flag{
lib.ConfigFilenameFlag,
cli.BoolFlag{
Name: "log-to-console",
Usage: "Log to STDERR, in addition to configured logging",
},
}
app.Action = func(context *cli.Context) {
os.Exit(connector(context))
}
Expand All @@ -48,15 +42,24 @@ func main() {
func connector(context *cli.Context) int {
config, configFilename, err := lib.GetConfig(context)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to read config file: %s", err)
fmt.Fprintf(os.Stderr, "Failed to read config file: %s\n", err)
return 1
}

log.SetLogToConsole(context.Bool("log-to-console"))
if interactive, err := svc.IsAnInteractiveSession(); err != nil {
fmt.Fprintf(os.Stderr, "Failed to detect interactive session: %s\n", err)
return 1
} else if !interactive {
err = log.SetLogToEventLog(true)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to start event log: %s\n", err)
return 1
}
}

logLevel, ok := log.LevelFromString(config.LogLevel)
if !ok {
fmt.Fprintf(os.Stderr, "Log level %s is not recognized", config.LogLevel)
fmt.Fprintf(os.Stderr, "Log level %s is not recognized\n", config.LogLevel)
return 1
}
log.SetLevel(logLevel)
Expand All @@ -66,7 +69,6 @@ func connector(context *cli.Context) int {
}

log.Info(lib.FullName)
fmt.Println(lib.FullName)

if !config.CloudPrintingEnable && !config.LocalPrintingEnable {
log.Fatal("Cannot run connector with both local_printing_enable and cloud_printing_enable set to false")
Expand Down Expand Up @@ -133,21 +135,16 @@ func connector(context *cli.Context) int {
if config.CloudPrintingEnable {
if config.LocalPrintingEnable {
log.Infof("Ready to rock as proxy '%s' and in local mode", config.ProxyName)
fmt.Printf("Ready to rock as proxy '%s' and in local mode\n", config.ProxyName)
} else {
log.Infof("Ready to rock as proxy '%s'", config.ProxyName)
fmt.Printf("Ready to rock as proxy '%s'\n", config.ProxyName)
}
} else {
log.Info("Ready to rock in local-only mode")
fmt.Println("Ready to rock in local-only mode")
}

waitIndefinitely()

log.Info("Shutting down")
fmt.Println("")
fmt.Println("Shutting down")

return 0
}
Expand All @@ -161,7 +158,7 @@ func waitIndefinitely() {
go func() {
// In case the process doesn't die quickly, wait for a second termination request.
<-ch
fmt.Println("Second termination request received")
log.Info("Second termination request received")
os.Exit(1)
}()
}
8 changes: 4 additions & 4 deletions lib/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import (
)

const (
ConnectorName = "Cloud Print Connector"

// A website with user-friendly information.
ConnectorHomeURL = "https://github.com/google/cups-connector"

Expand All @@ -30,16 +32,14 @@ var (
Usage: fmt.Sprintf("Connector config filename (default \"%s\")", defaultConfigFilename),
Value: defaultConfigFilename,
}
)

var (
// To be populated by something like:
// go install -ldflags "-X github.com/google/cups-connector/lib.BuildDate=`date +%Y.%m.%d`"
BuildDate = "DEV"

ShortName = "CUPS Connector " + BuildDate + "-" + runtime.GOOS
ShortName = platformName + " Connector " + BuildDate + "-" + runtime.GOOS

FullName = "Google Cloud Print CUPS Connector version " + BuildDate + "-" + runtime.GOOS
FullName = ConnectorName + " for " + platformName + " version " + BuildDate + "-" + runtime.GOOS
)

type commonConfig struct {
Expand Down
6 changes: 5 additions & 1 deletion lib/config_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ import (
"launchpad.net/go-xdg/v0"
)

const defaultConfigFilename = "gcp-cups-connector.config.json"
const (
platformName = "CUPS"

defaultConfigFilename = "gcp-cups-connector.config.json"
)

type Config struct {
// Associated with root account. XMPP credential.
Expand Down
6 changes: 5 additions & 1 deletion lib/config_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ import (
"github.com/codegangsta/cli"
)

const defaultConfigFilename = "gcp-windows-connector.config.json"
const (
platformName = "Windows"

defaultConfigFilename = "gcp-windows-connector.config.json"
)

type Config struct {
// Associated with root account. XMPP credential.
Expand Down
46 changes: 30 additions & 16 deletions log/log_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ package log
import (
"fmt"
"time"

"github.com/google/cups-connector/lib"
"golang.org/x/sys/windows/svc/eventlog"
)

const (
Expand All @@ -22,28 +25,34 @@ const (
)

var logger struct {
level LogLevel
logToStdout bool
logToEventLog bool
level LogLevel
elog *eventlog.Log
}

func init() {
logger.level = INFO
logger.logToStdout = false
logger.logToEventLog = true
}

// SetLevel sets the minimum severity level to log. Default is INFO.
func SetLevel(l LogLevel) {
logger.level = l
}

func SetLogToConsole(b bool) {
logger.logToStdout = b
}

func SetLogToEventLog(b bool) {
logger.logToEventLog = b
func SetLogToEventLog(b bool) error {
if b && logger.elog == nil {
l, err := eventlog.Open(lib.ConnectorName)
if err != nil {
return err
}
logger.elog = l
} else if !b && logger.elog != nil {
err := logger.elog.Close()
if err != nil {
return err
}
logger.elog = nil
}
return nil
}

func log(level LogLevel, printerID, jobID, format string, args ...interface{}) {
Expand All @@ -64,18 +73,23 @@ func log(level LogLevel, printerID, jobID, format string, args ...interface{}) {
message = fmt.Sprintf(logJobFormat, jobID, message)
}

if logger.logToStdout {
if logger.elog == nil {
dateTime := time.Now().Format(dateTimeFormat)
levelValue := stringByLevel[level]
fmt.Println(dateTime, levelValue, message)
}

if logger.logToEventLog {
} else {
if level == DEBUG || level == FATAL {
// Windows Event Log only has three levels; these two extra information prepended.
message = fmt.Sprintf("%s %s", stringByLevel[level], message)
}

// TODO
switch level {
case FATAL, ERROR:
logger.elog.Error(1, message)
case WARNING:
logger.elog.Warning(2, message)
case INFO, DEBUG:
logger.elog.Info(3, message)
}
}
}
2 changes: 1 addition & 1 deletion winspool/winspool.go
Original file line number Diff line number Diff line change
Expand Up @@ -628,7 +628,7 @@ func newJobContext(printerName, fileName, title string) (*jobContext, error) {
pDoc.Unref()
return nil, err
}
hDC, err := CreateDC(devMode.GetDeviceName(), devMode)
hDC, err := CreateDC(printerName, devMode)
if err != nil {
hPrinter.ClosePrinter()
pDoc.Unref()
Expand Down

0 comments on commit 9e41f0b

Please sign in to comment.