Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to write to a TcpStream without lots of write()s? #13

Closed
njam opened this issue Nov 19, 2018 · 1 comment
Closed

How to write to a TcpStream without lots of write()s? #13

njam opened this issue Nov 19, 2018 · 1 comment

Comments

@njam
Copy link
Collaborator

njam commented Nov 19, 2018

I'm currently using the Json drain to write to a TCP port like this:

    let writer = TcpStream::connect("localhost:5000").unwrap();
    let drain = slog_json::Json::default(writer);
    let logger = slog::Logger::root(Mutex::new(drain).map(slog::Fuse), o!());

The problem with this approach is that the JSON serializer will call write() on the TCP connection for every token ({, ", msg, ", : etc.). I believe this results in quite a performance hit.

I'm thinking to use a BufWriter around the TcpStream to allow buffering of the individual writes. To ensure that every log message is sent through the wire I'd want to call flush() after each message though.
Do you think that's a good solution?
I will open a pull request to add the flush() call if you agree.

njam added a commit to njam/json that referenced this issue Nov 19, 2018
njam added a commit to njam/json that referenced this issue Nov 20, 2018
njam added a commit to njam/json that referenced this issue Nov 20, 2018
@njam
Copy link
Collaborator Author

njam commented Nov 21, 2018

There's now the option to call set_flush(true) on the builder to enable flushing of the io::Write.

To create a buffered TCP writer, while flushing after each record:

let tcp_stream = TcpStream::connect("localhost:5000").unwrap();
let writer = BufWriter::new(tcp_stream);
let drain = slog_json::Json::new(writer).set_flush(true).build();
let logger = slog::Logger::root(Mutex::new(drain).map(slog::Fuse), o!());

@njam njam closed this as completed Nov 21, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant