How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Go · Go

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

goroutine 1 [running]: runtime/debug.Stack() /usr/local/go/src/runtime/debug/stack.go:24 +0x5e main.setupLogging() /app/logging/setup.go:15 +0x148 os.OpenFile({0x1028f1e60, 0x13}, 0x641, 0x1a4) /usr/local/go/src/os/file.go:331 +0x148 os.(*PathError).Error(0x14000196040) /usr/local/go/src/os/error.go:47 +0x48 main.main() /app/main.go:10 +0x48

Here's what each line means:

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.

Before (broken)
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)
}
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Run go test ./... locally to confirm file handling works.
  2. Open a pull request with the logging changes.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. 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.