Managing Logs with Docker Volumes
Learn about Docker volumes and how they can be used to manage and store logs.
We'll cover the following
So far, we've been using Go's log package to log messages and then Zap to add some structure to the logs. We 've also seen how we can either output the logs to the console or store them in a file. Saving logs to a file is obviously the preferable option in any real-world applications because we could need them later for debugging or analytics. But how does this work in the case of an app that is running inside a Docker container since we know that in such a case, any files created would reside inside the container and wouldn't be accessible from outside? Well, that's not strictly true. Let's see how.
Docker volumes
We've made changes to our app such that the logs get written in the app container. But how can we access them from outside the container? After all, that's where we will need them in order to check them. Besides, all local container files get destroyed if the container is destroyed. This will be highly undesirable because we won't be able to access logs to debug in case of a crash.
Docker Compose provides a simple solution to this. Docker volumes can be used in a Docker container to persist the data generated by the app inside the container. This is done by mapping a storage directory outside the container to one inside it.
It can be done either via the CLI using Docker commands or by making a few changes to the docker-compose.yml
file. Before we get into that, let's use Zap to store our logs files at a particular path.
Writing logs to a path
Let's set up logs in our app and store them in the file logs.txt
in the folder logs
as follows:
Get hands-on with 1400+ tech skills courses.