Skip to content

Commit 61264ed

Browse files
committed
Fix Issue 15771 - FileLogger should create the output directory if it does not exist
1 parent 0958adf commit 61264ed

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

std/experimental/logger/filelogger.d

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,31 @@ class FileLogger : Logger
2121
file can not be opened for writting an exception will be thrown.
2222
lv = The $(D LogLevel) for the $(D FileLogger). By default the
2323
$(D LogLevel) for $(D FileLogger) is $(D LogLevel.all).
24+
makeParentDirs = optional boolean value which specifies if the
25+
logging system should create the parent directoty structure. It
26+
defaults to false.
2427
2528
Example:
2629
-------------
2730
auto l1 = new FileLogger("logFile");
2831
auto l2 = new FileLogger("logFile", LogLevel.fatal);
32+
auto l3 = new FileLogger("/home/project/logs/logFile", LogLevel.fatal, true);
2933
-------------
3034
*/
31-
this(in string fn, const LogLevel lv = LogLevel.all) @safe
35+
this(in string fn, const LogLevel lv = LogLevel.all, bool makeParentDirs = false) @safe
3236
{
3337
super(lv);
3438
this.filename = fn;
39+
40+
if (makeParentDirs)
41+
{
42+
import std.path : dirName;
43+
import std.file : exists, mkdirRecurse;
44+
45+
auto dir = dirName(fn);
46+
if (!exists(dir))
47+
mkdirRecurse(dir);
48+
}
3549
this.file_.open(this.filename, "a");
3650
}
3751

@@ -158,6 +172,24 @@ class FileLogger : Logger
158172
assert(readLine.indexOf(notWritten) == -1, readLine);
159173
}
160174

175+
@system unittest
176+
{
177+
import std.file : rmdirRecurse, exists;
178+
179+
string filename = "bug15771/minas/oops/bug15771.txt";
180+
auto f = new FileLogger(filename, LogLevel.all, true);
181+
182+
scope(exit)
183+
{
184+
rmdirRecurse("bug15771");
185+
}
186+
187+
assert(exists("bug15771"));
188+
assert(exists("bug15771/minas"));
189+
assert(exists("bug15771/minas/oops"));
190+
assert(exists(filename));
191+
}
192+
161193
@system unittest
162194
{
163195
import std.array : empty;

0 commit comments

Comments
 (0)