Logrus logs keys alphabetically
No, it actually doesn't. A FieldMap
is actually just a standard go map (as you can see here). The same file shows how the JSON marshalling of the fieldmap is handled. There's nothing in there to suggest there's any specific key sorting being done.
It's well possible that, owing to how the map keys are hashed, the output is seemingly in alphabetical order in your specific case, on your platform, with your specific version of both logrus and the go compiler. There is, however, no guarantee that this will always be the case. If you compile the same code for a different architecture/operating system (GOARCH
and GOOS
), the output may not be the same. Things look to be in alphabetical order now, but that's just coincidence. Writing a test to ensure your luck hasn't run out isn't the point of tests.
Maps are, by definition, un-ordered data structures. If you want the log output to be ordered alphabetically, then you could write your own formatter for logrus, iterate over the fieldmap, add all the keys (as strings) to a slice, sort said slice, and then iterate over the sorted keys to print out the keys in alphabetical order. Then again, I would really be curious to know what your use-case is to justify such a thing.
Right, on closer inspection, it does seem that the encoding/json
package actually marshals maps as JSON objects, with keys being sorted:
Map values encode as JSON objects. The map's key type must either be a string, an integer type, or implement encoding.TextMarshaler
. The map keys are sorted and used as JSON object keys by applying the following rules, subject to the UTF-8 coercion described for string values above
That's fine, and provided the standard library doesn't change (or you don't decide to swap it out for some alternative that behaves differently), you should be good. This behaviour also isn't guaranteed when using a different formatter. Your outset was to ensure that replacing the logging package wouldn't break this behaviour. In that case, you're testing the wrong thing... it's not the logging package itself, but rather the json encoding package (marshaller) you're using.
You're basically looking for a way to test whether or not someone plugs in an alternative marshalling package into an external package you're using. If the next version of logrus ends up switching over to a package like ffjson
, your tests would fail, despite only having bumped the version of your log package, and making no other changes other than that. A unit test just isn't the best way to enforce this. You could maintain your own fork of the logrus package, or just lock in a known good version in your go.mod file instead, and call it a day.