Fix FilePermissionError: open /var/log/app.log: permission denied in Go
This error occurs when the Go process does not have filesystem permissions to read, write, or create the specified file. Common causes include running as a non-root user, incorrect directory ownership, or restrictive umask settings. Fix it by checking and setting proper file permissions with os.OpenFile, creating directories with os.MkdirAll, and handling permission errors gracefully.
Reading the Stack Trace
Here's what each line means:
- main.setupLogging() /app/logging/setup.go:15 +0x148: The setupLogging function at line 15 tries to open a log file in a directory the process does not have write access to.
- os.OpenFile({0x1028f1e60, 0x13}, 0x641, 0x1a4): OpenFile is called with O_CREATE|O_WRONLY|O_APPEND flags, but the OS denies the operation due to insufficient permissions.
- os.(*PathError).Error(0x14000196040): The OS returns a PathError with 'permission denied', indicating the process user lacks write access to the target path.
Common Causes
1. Writing to a root-owned directory as non-root user
The application tries to write to /var/log which requires root permissions, but the process runs as a non-root user.
func setupLogging() {
f, err := os.OpenFile("/var/log/app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
log.Fatal(err) // crashes on permission denied
}
log.SetOutput(f)
}
2. Directory does not exist
The parent directory for the file has not been created, and os.OpenFile cannot create intermediate directories.
f, err := os.Create("/app/data/logs/app.log")
// /app/data/logs/ does not exist
3. Docker container with read-only filesystem
The container runs with a read-only root filesystem, preventing file creation anywhere except mounted volumes.
// Dockerfile: read-only root filesystem
// The app tries to write to /tmp which is also read-only
The Fix
Use an environment variable for the log directory, create it with MkdirAll, and handle permission errors gracefully by falling back to stdout. This works in containers with read-only filesystems and avoids hardcoding paths that require root access.
func setupLogging() {
f, err := os.OpenFile("/var/log/app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
log.Fatal(err)
}
log.SetOutput(f)
}
func setupLogging() (*os.File, error) {
logDir := os.Getenv("LOG_DIR")
if logDir == "" {
logDir = "./logs"
}
if err := os.MkdirAll(logDir, 0o755); err != nil {
return nil, fmt.Errorf("creating log directory %s: %w", logDir, err)
}
logPath := filepath.Join(logDir, "app.log")
f, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
if err != nil {
if errors.Is(err, os.ErrPermission) {
log.Printf("WARNING: cannot write to %s, falling back to stdout", logPath)
return nil, nil // fall back to stdout
}
return nil, fmt.Errorf("opening log file %s: %w", logPath, err)
}
log.SetOutput(f)
return f, nil
}
Testing the Fix
package logging_test
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
func TestSetupLogging_CreatesDirectory(t *testing.T) {
dir := filepath.Join(t.TempDir(), "logs")
t.Setenv("LOG_DIR", dir)
f, err := setupLogging()
assert.NoError(t, err)
assert.NotNil(t, f)
defer f.Close()
_, err = os.Stat(filepath.Join(dir, "app.log"))
assert.NoError(t, err)
}
func TestSetupLogging_FallbackOnPermissionDenied(t *testing.T) {
t.Setenv("LOG_DIR", "/root/no-access")
f, err := setupLogging()
// Should fall back gracefully
assert.Nil(t, f)
assert.NoError(t, err)
}
Run your tests:
go test ./logging/... -v
Pushing Through CI/CD
git checkout -b fix/go-file-permission-error,git add logging/setup.go logging/setup_test.go,git commit -m "fix: use configurable log directory with fallback on permission denied",git push origin fix/go-file-permission-error
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.22'
- run: go mod download
- run: go vet ./...
- run: go test ./... -race -coverprofile=coverage.out
- run: go build ./...
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
go get github.com/bugstack/sdk
Step 2: Initialize
import "github.com/bugstack/sdk"
func init() {
bugstack.Init(os.Getenv("BUGSTACK_API_KEY"))
}
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run go test ./... locally to confirm file handling works.
- Open a pull request with the logging changes.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify log output in staging.
Frequently Asked Questions
BugStack tests with temporary directories, validates fallback behavior, and ensures the application starts correctly even when the log directory is not writable before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
Use 0644 (owner read/write, group/other read) for log files and 0755 for directories. Never use 0777 in production.
Log to stdout/stderr and let the container runtime handle log collection. Use volume mounts if you need file-based logging. Avoid writing to the container's root filesystem.