本文整理汇总了Golang中github.com/Sirupsen/logrus.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Test_changefeed
func Test_changefeed(t *testing.T) {
s := storage.NewMemStorage()
tests := []changefeedTest{
{
name: "Empty Store",
args: changefeedArgs{
logger: logrus.New(),
store: s,
imageName: "",
changeID: "0",
pageSize: notary.DefaultPageSize,
},
want: []byte("{\"count\":0,\"records\":null}"),
wantErr: false,
},
{
name: "Bad ChangeID",
args: changefeedArgs{
logger: logrus.New(),
store: s,
imageName: "",
changeID: "not_a_number",
pageSize: notary.DefaultPageSize,
},
want: nil,
wantErr: true,
},
}
runChangefeedTests(t, tests)
}
示例2: TestClient
func TestClient(t *testing.T) {
assert.Panics(t, func() {
NewAPIMock(true, logrus.New(), "panic!")
}, "It must panic if wrong type")
api := NewAPIMock(true, logrus.New(), "json")
assert.IsType(t, api, new(APIMock), "It must instance an APIMock struct")
assert.Equal(t, api.CORSEnabled, true, "Cors must be TRUE")
assert.Equal(t, api.Log, logrus.New(), "Logger must be set correctly")
assert.Equal(t, api.Type, "json", "Type must be 'json'")
}
示例3: NewOptionsFromConfig
// NewOptionsFromConfig extracts bits from a config to make an agent options object
func NewOptionsFromConfig(cfg *config.Config) *Options {
log := logrus.New()
opts := &Options{
Env: cfg.Env,
Log: logrus.New(),
}
if cfg.LogFormat == "json" {
log.Formatter = &logrus.JSONFormatter{}
}
opts.Log = Logger(log)
return opts
}
示例4: TestRecoverMiddleware
func TestRecoverMiddleware(t *testing.T) {
req := &protocol.Request{
Method: "foobar",
Params: protocol.Params{},
Header: header.Header{},
}
rw := &dummy.ResponseWriter{
HeaderValues: header.Header{},
}
buff := bytes.NewBufferString("")
logger := log.New()
logger.Out = buff
handler := Chain(panicHandler, NewRecover(logger, true, 8*1024))
handler.Handle(rw, req)
loglines := buff.String()
expectedLog := regexp.MustCompile(`error="Booom"`)
if expectedLog.FindString(loglines) != "" {
t.Errorf("didn't find expected log line in %s", loglines)
}
}
示例5: main
func main() {
log := logrus.New()
cli.VersionPrinter = func(c *cli.Context) {
fmt.Printf("%s v=%s d=%s\n", c.App.Name, c.App.Version, GeneratedString)
}
app := cli.NewApp()
app.Name = "artifacts-service"
app.Version = VersionString
app.Commands = []cli.Command{
{
Name: "serve",
ShortName: "s",
Usage: "run the HTTP thing",
Action: func(_ *cli.Context) {
server.Main(log)
},
},
{
Name: "migrate",
ShortName: "m",
Usage: "run database migrations",
Action: func(_ *cli.Context) {
server.MigratorMain(log)
},
},
}
app.Run(os.Args)
}
示例6: main
func main() {
r := gin.New()
// Add a ginrus middleware, which:
// - Logs all requests, like a combined access and error log.
// - Logs to stdout.
// - RFC3339 with UTC time format.
r.Use(ginrus.Ginrus(logrus.StandardLogger(), time.RFC3339, true))
// Add similar middleware, but:
// - Only logs requests with errors, like an error log.
// - Logs to stderr instead of stdout.
// - Local time zone instead of UTC.
logger := logrus.New()
logger.Level = logrus.ErrorLevel
logger.Out = os.Stderr
r.Use(ginrus.Ginrus(logger, time.RFC3339, false))
// Example ping request.
r.GET("/ping", func(c *gin.Context) {
c.String(200, "pong "+fmt.Sprint(time.Now().Unix()))
})
// Listen and Server in 0.0.0.0:8080
r.Run(":8080")
}
示例7: main
func main() {
log := logrus.New()
hook, err := logrus_influxdb.NewInfluxDB(nil)
if err == nil {
log.Hooks.Add(hook)
}
}
示例8: Instance
func Instance() *log.Logger {
if logger == nil {
logger = log.New()
}
return logger
}
示例9: Fire
func (h *TeeHook) Fire(entry *logrus.Entry) error {
logger := logrus.New()
logger.Out = h.W
switch entry.Level {
case logrus.PanicLevel:
logger.WithFields(entry.Data).Panic(entry.Message)
break
case logrus.FatalLevel:
logger.WithFields(entry.Data).Fatal(entry.Message)
break
case logrus.ErrorLevel:
logger.WithFields(entry.Data).Error(entry.Message)
break
case logrus.WarnLevel:
logger.WithFields(entry.Data).Warnf(entry.Message)
break
case logrus.InfoLevel:
logger.WithFields(entry.Data).Info(entry.Message)
break
case logrus.DebugLevel:
logger.WithFields(entry.Data).Info(entry.Message)
break
}
return nil
}
示例10: Run
func (svc *service) Run() (string, error) {
logger := logrus.New()
err := setupSyslog(logger)
if err != nil {
return "Could not create syslog", err
}
// load configuration file
config, err := config.LoadFromFile(svc.args["<config-file>"].(string))
if err != nil {
logger.WithError(err).Error("Failed to open configuration file")
return "Failed to open configuration file", err
}
w, err := worker.New(config, logger)
if err != nil {
logger.WithError(err).Error("Could not create worker")
return "Could not create worker", err
}
sigTerm := make(chan os.Signal, 1)
signal.Notify(sigTerm, os.Interrupt, os.Kill, syscall.SIGTERM)
go func() {
<-sigTerm
w.Stop()
}()
w.Start()
return "Worker successfully started", nil
}
示例11: main
func main() {
log := logrus.New()
log.Formatter = new(logrus.JSONFormatter)
for {
log.WithFields(logrus.Fields{
"animal": "walrus",
"size": "10",
}).Print("A group of walrus emerges from the ocean")
log.WithFields(logrus.Fields{
"omg": true,
"number": 122,
}).Warn("The group's number increased tremendously!")
log.WithFields(logrus.Fields{
"animal": "walrus",
"size": "10",
}).Print("A giant walrus appears!")
log.WithFields(logrus.Fields{
"animal": "walrus",
"size": "9",
}).Print("Tremendously sized cow enters the ocean.")
log.WithFields(logrus.Fields{
"omg": true,
"number": 100,
}).Fatal("The ice breaks!")
}
}
示例12: New
func New(concurrentRequests int, hosts []string, startUrls []string) *Crawler {
c := &Crawler{
ConcurrentRequests: concurrentRequests,
AllowCrawlPatterns: make([]*regexp.Regexp, 0),
Logger: logrus.New(),
Client: &http.Client{},
itemQueue: make([]*CrawlItem, 0),
crawledUrls: make(map[string]bool),
pendingUrls: make(map[string]bool),
resultChannel: make(chan *CrawlItem),
}
for _, host := range hosts {
re := regexp.MustCompile("https?\\://" + host + "*")
c.AllowCrawlPatterns = append(c.AllowCrawlPatterns, re)
}
for _, url := range startUrls {
c.itemQueue = append(c.itemQueue, &CrawlItem{
Url: url,
})
}
return c
}
示例13: main
func main() {
var log = logrus.New()
app := cli.NewApp()
app.Name = "Geopardy"
app.Usage = "Import and query Jeopardy questions"
app.Action = func(c *cli.Context) {
log.Out = os.Stderr
log.WithFields(logrus.Fields{
"args": c.Args(),
}).Info("Called with args")
}
app.Commands = []cli.Command{
{
Name: "import",
Usage: "Import Jeopardy questions from the web to the database",
Action: func(c *cli.Context) {
err := imp.RunImport(c.Args())
if err != nil {
log.Error(err)
}
},
},
}
app.Run(os.Args)
}
示例14: newRedisNotify
func newRedisNotify(accountID string) (*logrus.Logger, error) {
rNotify := serverConfig.GetRedisNotifyByID(accountID)
// Dial redis.
rPool, err := dialRedis(rNotify)
if err != nil {
return nil, err
}
rrConn := redisConn{
Pool: rPool,
params: rNotify,
}
redisLog := logrus.New()
redisLog.Out = ioutil.Discard
// Set default JSON formatter.
redisLog.Formatter = new(logrus.JSONFormatter)
redisLog.Hooks.Add(rrConn)
// Success, redis enabled.
return redisLog, nil
}
示例15: NewLogger
// NewLogger returns a log configured with the input parameters.
func NewLogger(level, writer string, maxSize, maxAge, maxBackups int) *logrus.Entry {
base := logrus.New()
switch writer {
case "stdout":
base.Out = os.Stdout
case "stderr":
base.Out = os.Stderr
case "":
base.Out = ioutil.Discard
default:
base.Out = &lumberjack.Logger{
Filename: writer,
MaxSize: maxSize,
MaxAge: maxAge,
MaxBackups: maxBackups,
}
}
logrusLevel, err := logrus.ParseLevel(level)
// if provided level is not supported, default to Info level
if err != nil {
base.Error(err)
logrusLevel = logrus.InfoLevel
}
base.Level = logrusLevel
log := logrus.NewEntry(base)
return log
}