@@ -50,7 +50,7 @@ func (r *RootCmd) ssh() *clibase.Cmd {
50
50
identityAgent string
51
51
wsPollInterval time.Duration
52
52
noWait bool
53
- logFilePath string
53
+ logDirPath string
54
54
)
55
55
client := new (codersdk.Client )
56
56
cmd := & clibase.Cmd {
@@ -73,11 +73,33 @@ func (r *RootCmd) ssh() *clibase.Cmd {
73
73
logger .Error (ctx , "command exit" , slog .Error (retErr ))
74
74
}
75
75
}()
76
- if logFilePath != "" {
77
- logFile , err := os . OpenFile ( logFilePath , os . O_CREATE | os . O_APPEND | os . O_WRONLY , 0o600 )
76
+ if logDirPath != "" {
77
+ nonce , err := cryptorand . StringCharset ( cryptorand . Lower , 5 )
78
78
if err != nil {
79
- return xerrors . Errorf ( "error opening %s for logging: %w" , logFilePath , err )
79
+ panic ( err )
80
80
}
81
+ logFilePath := filepath .Join (
82
+ logDirPath ,
83
+ fmt .Sprintf (
84
+ "coder-ssh-%s-%s.log" ,
85
+ // The time portion makes it easier to find the right
86
+ // log file.
87
+ time .Now ().Format ("20060102-150405" ),
88
+ // The nonce prevents collisions, as SSH invocations
89
+ // frequently happen in parallel.
90
+ nonce ,
91
+ ),
92
+ )
93
+ logFile , err := os .OpenFile (
94
+ logFilePath ,
95
+ os .O_CREATE | os .O_APPEND | os .O_WRONLY | os .O_EXCL ,
96
+ 0o600 ,
97
+ )
98
+ if err != nil {
99
+ return xerrors .Errorf ("error opening %s for logging: %w" , logDirPath , err )
100
+ }
101
+ defer logFile .Close ()
102
+
81
103
logger = slog .Make (sloghuman .Sink (logFile ))
82
104
if r .verbose {
83
105
logger = logger .Leveled (slog .LevelDebug )
@@ -359,11 +381,11 @@ func (r *RootCmd) ssh() *clibase.Cmd {
359
381
Value : clibase .BoolOf (& noWait ),
360
382
},
361
383
{
362
- Flag : "log-file " ,
363
- Description : "Specify the location of an SSH diagnostic log file ." ,
364
- Env : "CODER_SSH_LOG_FILE " ,
384
+ Flag : "log-dir " ,
385
+ Description : "Specify the directory containing SSH diagnostic log files ." ,
386
+ Env : "CODER_SSH_LOG_DIR " ,
365
387
FlagShorthand : "l" ,
366
- Value : clibase .StringOf (& logFilePath ),
388
+ Value : clibase .StringOf (& logDirPath ),
367
389
},
368
390
}
369
391
return cmd
0 commit comments