Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

promlog: add support for json logger #136

Merged
merged 1 commit into from
Nov 13, 2018
Merged

promlog: add support for json logger #136

merged 1 commit into from
Nov 13, 2018

Conversation

alexander-yu
Copy link
Contributor

@alexander-yu alexander-yu commented May 22, 2018

Note: this changes the signature of promlog.New, so any repos that use this method in prometheus will need to be changed and will need to include the log.format flag.

As far as I'm aware, functions whose signatures are affected (i.e. promlog.New and flag.AddFlags) are used in prometheus/cmd/prometheus/main.go, alertmanager/cmd/alertmanager/main.go, and blackbox_exporter/main.go, so these will need to be updated at some point, at least when the vendor directories are updated.

Fixes issue: prometheus/prometheus#3219

Should I include some sort of test for this feature (and maybe the log level flag as well)?

@krasi-georgiev

@brian-brazil
Copy link
Contributor

This shouldn't require an API change, this should always default to what we already do.

@alexander-yu
Copy link
Contributor Author

Fair enough; would it be better to add a new method like promlog.NewJSON? Also, should flag.AddFlags remain modified, or should there also be a separate method for adding the format flag?

@brian-brazil
Copy link
Contributor

The whole point of this design is that changes to the log library should only require a revendoring, no code changes.

@alexander-yu
Copy link
Contributor Author

Yes, that makes sense; I was only asking about flag.AddFlags because its name (and its commented description) seems to imply semantically that it should be for adding any flags used in the package, but its signature right now is fixed at only supporting a single flag (i.e. the log level).

@brian-brazil
Copy link
Contributor

The function allows you to change the default flag value for that one flag. There's no need for the others to have defaults.

@alexander-yu
Copy link
Contributor Author

@brian-brazil any thoughts on the PR as it is? It's been modified so that an API change isn't necessary.

@ntindall
Copy link

ntindall commented Jul 1, 2018

@krasi-georgiev @brian-brazil would love to see this into the prometheus mainline - I think this change is sufficient to facilitate some minor changes to cmd.

@ntindall
Copy link

@alexander-yu any idea why the CI is failing?

@alexander-yu
Copy link
Contributor Author

It's due to an earlier merged PR -- #134 is a fix for it, I believe.

// AddFlags adds the flags used by this package to the Kingpin application.
// To use the default Kingpin application, call AddFlags(kingpin.CommandLine)
func AddFlags(a *kingpin.Application, logLevel *promlog.AllowedLevel) {
a.Flag(LevelFlagName, LevelFlagHelp).
Default("info").SetValue(logLevel)

a.Flag(FormatFlagName, FormatFlagHelp).
Default("logfmt").Enum("logfmt", "json")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I might be missing something obvious but I don't see how this is going to work for Prometheus. How will the main() know about the flag's value?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It shouldn't need to.

@ntindall
Copy link

@brian-brazil what do we need to do to get this in?

promlog/log.go Outdated

// NewJSON returns a new leveled oklog logger in the JSON format. Each logged line will be annotated
// with a timestamp. The output always goes to stderr.
func NewJSON(al AllowedLevel) log.Logger {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This shouldn't be here. This is something for the user to configure, not the developer.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you recommend that this function instead exist wherever users within prometheus are setting up their loggers? It made sense to put this in the same place as New, since these are doing equivalent things, except with different loggers.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function shouldn't exist at all.

@alexander-yu
Copy link
Contributor Author

@brian-brazil Removed the NewJSON function, also rebased.

@brian-brazil
Copy link
Contributor

How does this code actually set the level? It just seems to be creating a flag.

@alexander-yu
Copy link
Contributor Author

alexander-yu commented Sep 11, 2018

As a flag? That should be set already by AddFlags (and then by the user of this parsing command args). If you mean setting the log level to the JSON logger, that's what the NewJSON function (now removed) was doing, which is functionality that (now) should be done by the user of the flag.

The problem with the current PR is that the user doesn't really have a way to access this flag; could be done by modifying the signature of AddFlags to take a *string as an argument. It would require changes on users within prometheus that call this method, though, which is a concern that you already brought up earlier. Here for example, it would want to pass in a pointer to a string var that has this flag, and then sets up the JSON logger if necessary, probably around here.

Alternatively, do you prefer that any part of prometheus that wants to have support for a JSON logger manually do the setup themselves, rather than providing for that functionality here? If so, I can instead make PRs in the corresponding places.

@brian-brazil
Copy link
Contributor

The various flags, current and future, should be opaque to any users of this library. Can you suggest something that'd achieve that, even if it requires one-off changes to existing users?

@alexander-yu
Copy link
Contributor Author

Sure; so thinking about it some more, we could do something that mirrors how the log level is currently set; we could have a struct AllowedFormat that looks like this:

type AllowedFormat struct {
	s string
}

func (l *AllowedFormat) String() string {
	return l.s
}

func (l *AllowedLevel) Set(s string) error {
	switch s {
	case "logfmt", "json":
		l.s = s
	default:
		return errors.Errorf("unrecognized log format %q", s)
	}
	return nil
}

which makes sure that we can only have the two specified formats. We'd then have AddFlags look like this:

func AddFlags(a *kingpin.Application, logLevel *promlog.AllowedLevel, logFormat *promlog.AllowedFormat) {
	a.Flag(LevelFlagName, LevelFlagHelp).
		Default("info").SetValue(logLevel)
	a.Flag(FormatFlagName, FormatFlagHelp).
		Default("logfmt").SetValue(logFormat)
}

so it'll set the value of the log format for whatever user is calling this method.

If we wanted to keep the exact internal values of the AllowedFormat flag isolated from users, then we could modify the New logger method to look like:

func New(al AllowedLevel, af AllowedFormat) log.Logger {
	var l log.Logger
	if af.s == "logfmt" {
		l = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
	} else {
		l = log.NewJSONLogger(log.NewSyncWriter(os.Stderr))
	}
	
	l = level.NewFilter(l, al.o)
	l = log.With(l, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller)
	return l
}

then on the client side, we might have something like this:

promlogflag.AddFlags(a, &cfg.logLevel, &cfg.logFormat)
...
logger := promlog.New(cfg.logLevel, cfg.logFormat)

So on the client side, this means that there are three things they'd need to do to support this, which could easily be done in a single PR:

  • Provide some promlog.AllowedFormat var (potentially as an additional config field, or just as a one-off var) to store the flag value
  • Modify the call to AddFlags
  • Modify the call to New

@brian-brazil
Copy link
Contributor

When the next setting comes along, that'd require every user of this code to change their code - not just their vendoring.

@brian-brazil
Copy link
Contributor

We probably need either an opaque struct, or that the initialisation function looks at the flag globals.

@alexander-yu
Copy link
Contributor Author

alexander-yu commented Sep 12, 2018

Sorry I deleted my comment; was writing this up instead.

Right, that makes sense; I was thinking we change AddFlags and New to look like:

func AddFlags(a *kingpin.Application, config *promlog.Config) {
    ...
}

func New(config *promlog.Config) {
    ...
}

where the config struct looks like:

type Config struct {
    level  *AllowedLevel
    format *AllowedFormat
}

This way the clients only need to change the calls once; if we want to add more settings we simply add fields to the struct, and clients can choose whether or not to instantiate these fields whenever they want; revendoring only means that the new fields aren't populated (and probably set to some default when AddFlags is called).

@brian-brazil
Copy link
Contributor

That seems fine to me. Though the fields are private so can't be changed by users, which seems fine too.

Fixes issue: prometheus/prometheus#3219

Signed-off-by: Alex Yu <yu.alex96@gmail.com>
@alexander-yu
Copy link
Contributor Author

Sounds great; I incorporated the changes, though I had to make the fields public/exported, since flag.go needs access to those fields.

@carlpett
Copy link
Member

Are there any blockers for merging this still?

@brian-brazil
Copy link
Contributor

That looks about right, but we should wait for 2.5 to be out before merging.

@carlpett
Copy link
Member

So, that would be about now then? :)
Sorry for the nagging

@brian-brazil brian-brazil merged commit 41aa239 into prometheus:master Nov 13, 2018
@brian-brazil
Copy link
Contributor

Thanks!

Next you'll need to update the repos using this.

@ntindall
Copy link

ntindall commented Dec 6, 2018

🎉 !

razius added a commit to razius/domain_exporter that referenced this pull request Jan 1, 2019
Fixes invalid type being passes to the constructor:

```
cannot use &allowedLevel (type *promlog.AllowedLevel) as type *promlog.Config in argument to flag.AddFlags
```

See following for more info: prometheus/common#136
alanprot pushed a commit to alanprot/common that referenced this pull request Mar 15, 2023
d6cc704 Fix comment
7139116 Revert "Push comments to the left so they don't appear in scripts"
e47e58f Push comments to the left so they don't appear in scripts
3945fce Remove nonexistent env var GIT_TAG
cd62992 Merge pull request prometheus#156 from weaveworks/drop-quay
af0eb51 Merge pull request prometheus#157 from weaveworks/fix-image-tag-prefix-length
0b9aee4 Fix image-tag object name prefix length to 8 chars.
813c28f Move from CircleCI 1.0 to 2.0
425cf4e Move from quay.io to Dockerhub
87ccf4f Merge pull request prometheus#155 from weaveworks/go-1-12
c31bc28 Update lint script to work with Go 1.12
ed8e380 Update to Go 1.12.1
ec369f5 Merge pull request prometheus#153 from dholbach/drop-email
ef7418d weave-users mailing list is closed: https://groups.google.com/a/weave.works/forum/#!topic/weave-users/0QXWGOPdBfY
6954a57 Merge pull request prometheus#144 from weaveworks/golang-1.11.1
9649eed Upgrade build image from golang:1.10.0-strech to 1.11.1-strech
59263a7 Merge pull request prometheus#141 from weaveworks/update-context
e235c9b Merge pull request prometheus#143 from weaveworks/gc-wks-test-vms
c865b4c scheduler: please lint/flake8
da61568 scheduler: please lint/yapf
ce9d78e scheduler: do not cache discovery doc
e4b7873 scheduler: add comment about GCP projects' IAM roles needed to list/delete instances and firewall rules
ff7ec8e scheduler: add comment about CircleCI projects' access via the API
2477d98 scheduler: deploy command now sets the current datetime as the version
5fcd880 scheduler: pass CircleCI API token in for private projects
6b8c323 scheduler: more details in case of failure to get running builds from CircleCI
0871aff scheduler: downgrade google-api-python-client from 1.7.4 to 1.6.7
b631e7f scheduler: add GC of WKS test VMs and firewall rules
a923a32 scheduler: document setup and deployment
013f508 scheduler: lock dependencies' versions
6965a4a Merge pull request prometheus#142 from weaveworks/fix-build
23298c6 Fix golint expects import golang.org/x/lint/golint
482f4cd Context is now part of the Go standard library
2bbc9a0 Merge pull request prometheus#140 from weaveworks/sched-http-retry
c3726de Add retries to sched util http calls
2cc7b5a Merge pull request prometheus#139 from meghalidhoble/master
fd9b0a7 Change : Modified the lint tools to skip the shfmt check if not installed. Why the change : For ppc64le the specific version of shfmt is not available, hence skipped completely the installation of shfmt tool. Thus this change made.
bc645c7 Merge pull request prometheus#138 from dholbach/add-license-file
a642e02 license: add Apache 2.0 license text
9bf5956 Merge pull request prometheus#109 from hallum/master
d971d82 Merge pull request prometheus#134 from weaveworks/2018-07-03-gcloud-regepx
32e7aa2 Merge pull request prometheus#137 from weaveworks/gcp-fw-allow-kube-apiserver
bbb6735 Allow CI to access k8s API server on GCP instances
764d46c Merge pull request prometheus#135 from weaveworks/2018-07-04-docker-ansible-playbook
ecc2a4e Merge pull request prometheus#136 from weaveworks/2018-07-05-gcp-private-ips
209b7fb tools: Add private_ips to the terraform output
369a655 tools: Add an ansible playbook that just installs docker
a643e27 tools: Use --filter instead of --regexp with gcloud
b8eca88 Merge pull request prometheus#128 from weaveworks/actually-say-whats-wrong
379ce2b Merge pull request prometheus#133 from weaveworks/fix-decrypt
3b906b5 Fix incompatibility with recent versions of OpenSSL
f091ab4 Merge pull request prometheus#132 from weaveworks/add-opencontainers-labels-to-dockerfiles
248def1 Inject git revision in Dockerfiles
64f2c28 Add org.opencontainers.image.* labels to Dockerfiles
ea96d8e add information about how to get help (prometheus#129)
f066ccd Make yapf diff failure look like an error
34d81d7 Merge pull request prometheus#127 from weaveworks/golang-1.10.0-stretch
89a0b4f Use golang:1.10.0-stretch image.
ca69607 Merge pull request prometheus#126 from weaveworks/disable-apt-daily-test
f5dc5d5 Create "setup-apt" role
7fab441 Rename bazel to bazel-rules (prometheus#125)
ccc8316 Revert "Gocyclo should return error code if issues detected" (prometheus#124)
1fe184f Bazel rules for building gogo protobufs (prometheus#123)
b917bb8 Merge pull request prometheus#122 from weaveworks/fix-scope-gc
c029ce0 Add regex to match scope VMs
0d4824b Merge pull request prometheus#121 from weaveworks/provisioning-readme-terraform
5a82d64 Move terraform instructions to tf section
d285d78 Merge pull request prometheus#120 from weaveworks/gocyclo-return-value
76b94a4 Do not spawn subshell when reading cyclo output
93b3c0d Use golang:1.9.2-stretch image
d40728f Gocyclo should return error code if issues detected
c4ac1c3 Merge pull request prometheus#114 from weaveworks/tune-spell-check
8980656 Only check files
12ebc73 Don't spell-check pki files
578904a Special-case spell-check the same way we do code checks
e772ed5 Special-case on mime type and extension using just patterns
ae82b50 Merge pull request prometheus#117 from weaveworks/test-verbose
8943473 Propagate verbose flag to 'go test'.
7c79b43 Merge pull request prometheus#113 from weaveworks/update-shfmt-instructions
258ef01 Merge pull request prometheus#115 from weaveworks/extra-linting
e690202 Use tools in built image to lint itself
126eb56 Add shellcheck to bring linting in line with scope
63ad68f Don't run lint on files under .git
51d908a Update shfmt instructions
e91cb0d Merge pull request prometheus#112 from weaveworks/add-python-lint-tools
0c87554 Add yapf and flake8 to golang build image
35679ee Merge pull request prometheus#110 from weaveworks/parallel-push-errors
3ae41b6 Remove unneeded if block
51ff31a Exit on first error
0faad9f Check for errors when pushing images in parallel
d87cd02 Add arg flag override for destination socks host:port in pacfile.
74dc626 Merge pull request prometheus#108 from weaveworks/disable-apt-daily
b4f1d91 Merge pull request prometheus#107 from weaveworks/docker-17-update
7436aa1 Override apt daily job to not run immediately on boot
7980f15 Merge pull request prometheus#106 from weaveworks/document-docker-install-role
f741e53 Bump to Docker 17.06 from CE repo
61796a1 Update Docker CE Debian repo details
0d86f5e Allow for Docker package to be named docker-ce
065c68d Document selection of Docker installation role.
3809053 Just --porcelain; it defaults to v1
11400ea Merge pull request prometheus#105 from weaveworks/remove-weaveplugin-remnants
b8b4d64 remove weaveplugin remnants
35099c9 Merge pull request prometheus#104 from weaveworks/pull-docker-py
cdd48fc Pull docker-py to speed tests/builds up.
e1c6c24 Merge pull request prometheus#103 from weaveworks/test-build-tags
d5d71e0 Add -tags option so callers can pass in build tags
8949b2b Merge pull request prometheus#98 from weaveworks/git-status-tag
ac30687 Merge pull request prometheus#100 from weaveworks/python_linting
4b125b5 Pin yapf & flake8 versions
7efb485 Lint python linting function
444755b Swap diff direction to reflect changes required
c5b2434 Install flake8 & yapf
5600eac Lint python in build-tools repo
0b02ca9 Add python linting
c011c0d Merge pull request prometheus#79 from kinvolk/schu/python-shebang
6577d07 Merge pull request prometheus#99 from weaveworks/shfmt-version
00ce0dc Use git status instead of diff to add 'WIP' tag
411fd13 Use shfmt v1.3.0 instead of latest from master.
0d6d4da Run shfmt 1.3 on the code.
5cdba32 Add sudo
c322ca8 circle.yml: Install shfmt binary.
e59c225 Install shfmt 1.3 binary.
30706e6 Install pyhcl in the build container.
960d222 Merge pull request prometheus#97 from kinvolk/alban/update-shfmt-3
1d535c7 shellcheck: fix escaping issue
5542498 Merge pull request prometheus#96 from kinvolk/alban/update-shfmt-2
32f7cc5 shfmt: fix coding style
09f72af lint: print the diff in case of error
571c7d7 Merge pull request prometheus#95 from kinvolk/alban/update-shfmt
bead6ed Update for latest shfmt
b08dc4d Update for latest shfmt (prometheus#94)
2ed8aaa Add no-race argument to test script (prometheus#92)
80dd78e Merge pull request prometheus#91 from weaveworks/upgrade-go-1.8.1
08dcd0d Please ./lint as shfmt changed its rules between 1.0.0 and 1.3.0.
a8bc9ab Upgrade default Go version to 1.8.1.
31d069d Change Python shebang to `#!/usr/bin/env python`

git-subtree-dir: tools
git-subtree-split: d6cc704a2892e8d85aa8fa4d201c1a404f02dfa4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants