Created
April 15, 2021 08:00
-
-
Save adzimzf/bf4d7c9d30a57b902d8ab7c2b88b13a8 to your computer and use it in GitHub Desktop.
redirect stderr & stdout to file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"syscall" | |
) | |
func main() { | |
filename := "/home/test.log" | |
logFile, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) | |
if err != nil { | |
log.Println("Error in opening ", filename, err) | |
os.Exit(2) | |
} | |
// stdout | |
if err = syscall.Dup2(int(logFile.Fd()), 1); err != nil { | |
log.Println("Failed to dup", filename) | |
} | |
// stderr | |
if err = syscall.Dup2(int(logFile.Fd()), 2); err != nil { | |
log.Println("Failed to dup", filename) | |
} | |
log.Println("test") | |
fmt.Println("test") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment