Last active
August 29, 2015 14:21
-
-
Save erica/0ff801ff80371c4b0c43 to your computer and use it in GitHub Desktop.
swlog
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
public struct StderrOutputStream: OutputStreamType { | |
// Support for file redirection back to console | |
private static var fpos : fpos_t = 0 | |
private static var fd = dup(fileno(stderr)) | |
private static var isRedirected_ = false | |
public static var isRedirected : Bool {return isRedirected_} | |
// When false, the output file is rewritten and not appended | |
private static var appendToFile = true | |
// When true, output is echoed to stdout | |
public static var echo = false | |
// When non-nil, output is redirected to the specified file path | |
public static func redirectOutputToPath(path: String?) { | |
if let path = path { | |
if !isRedirected { | |
// Set up if this is new redirection | |
fflush(stderr) | |
var pos = UnsafeMutablePointer<fpos_t>.alloc(1) | |
fgetpos(stderr, pos) | |
fpos = pos.memory | |
free(pos) | |
fd = dup(fileno(stderr)) | |
} | |
if appendToFile { | |
freopen(path, "a", stderr) | |
} else { | |
freopen(path, "w", stderr) | |
} | |
isRedirected_ = true | |
} else { | |
if !isRedirected { | |
// do not respond if not redirected | |
return | |
} | |
fflush(stderr) | |
dup2(fd, fileno(stderr)) | |
close(fd) | |
clearerr(stderr) | |
fsetpos(stderr, &fpos) | |
isRedirected_ = false | |
} | |
} | |
public static let stream = StderrOutputStream() | |
public func write(string: String) { | |
fputs(string, stderr) | |
if StderrOutputStream.echo && StderrOutputStream.isRedirected {fputs(string, stdout)} | |
} | |
} | |
public var errStream = StderrOutputStream.stream | |
func swlog(format : String, args : CVarArgType...) { | |
println(String(format: format, arguments: args), &errStream) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What's with the underscore suffix in your private member -
private static var isRedirected_ = false
Is this just a preference vs a prefixed underscore or is this preferred in Swift?