Home > Software design >  What means "package-level exported"
What means "package-level exported"

Time:12-07

I was looking into this logger. What this import exactly means?

The simplest way to use Logrus is simply the package-level exported logger:

package main

import (
  log "github.com/sirupsen/logrus"
)

func main() {
  log.WithFields(log.Fields{
    "animal": "walrus",
  }).Info("A walrus appears")
}

From the example it looks like that "built-in" log was replaces by the the above implementation. I couldn't locate any official/formal specs, probably I don't know how this feature is called.

CodePudding user response:

This is simply a reference to the fact that there are functions exported directly at the package level. That is, they do not require any type or variable reference to access those exported symbols.

The example in the.. um.. example, is the WithFields() function.

This is exported at that "package level", so all you need in order to reference that function is the package name (or alias).

In this case, the logrus package has been aliased as log, so the WithFields() function it exports can be called simply using:

    log.WithFields(/* etc */)

By contrast, the Info() function in the example illustrates a symbol (in this case a function) exported by another type in the logrus package; the Info() function here is called on a logrus.Entry reference (returned by the WithFields() function).

What's the Big Deal?

Package-Level exports are very common in go; a package that didn't export anything wouldn't be very useful to anybody! :)

I'm not sure that they are explicitly referenced as "package-level" exports in general; usually they would just be "exports" or "exported symbols" etc.

They are called out specifically in the case of logrus because the package authors have used this to create a package that is 'compatible' with the standard log package in GoLang (which also uses "package-level" exports).

i.e. if you alias logrus as log then logrus provides a superset of the standard log package; this is deliberately so that existing code that uses the log package can be converted to logrus very quickly by simply changing the import statement in files that make log calls.

  •  Tags:  
  • go
  • Related