Giter Club home page Giter Club logo

logger's Introduction

Iron

Build Status Crates.io Status License

Extensible, Concurrency Focused Web Development in Rust.

Response Timer Example

Note: This example works with the current iron code in this repository (master branch). If you are using iron 0.6 from crates.io, please refer to the corresponding example in the branch 0.6-maintenance.

extern crate iron;
extern crate time;

use iron::prelude::*;
use iron::{typemap, AfterMiddleware, BeforeMiddleware};
use time::precise_time_ns;

struct ResponseTime;

impl typemap::Key for ResponseTime { type Value = u64; }

impl BeforeMiddleware for ResponseTime {
    fn before(&self, req: &mut Request) -> IronResult<()> {
        req.extensions.insert::<ResponseTime>(precise_time_ns());
        Ok(())
    }
}

impl AfterMiddleware for ResponseTime {
    fn after(&self, req: &mut Request, res: Response) -> IronResult<Response> {
        let delta = precise_time_ns() - *req.extensions.get::<ResponseTime>().unwrap();
        println!("Request took: {} ms", (delta as f64) / 1000000.0);
        Ok(res)
    }
}

fn hello_world(_: &mut Request) -> IronResult<Response> {
    Ok(Response::with((iron::StatusCode::OK, "Hello World")))
}

fn main() {
    let mut chain = Chain::new(hello_world);
    chain.link_before(ResponseTime);
    chain.link_after(ResponseTime);
    Iron::new(chain).http("localhost:3000");
}

Overview

Iron is a high level web framework built in and for Rust, built on hyper. Iron is designed to take advantage of Rust's greatest features - its excellent type system and its principled approach to ownership in both single threaded and multi threaded contexts.

Iron is highly concurrent and can scale horizontally on more machines behind a load balancer or by running more threads on a more powerful machine. Iron avoids the bottlenecks encountered in highly concurrent code by avoiding shared writes and locking in the core framework.

Iron is 100% safe code:

$ rg unsafe src | wc
       0       0       0

Philosophy

Iron is meant to be as extensible and pluggable as possible; Iron's core is concentrated and avoids unnecessary features by leaving them to middleware, plugins, and modifiers.

Middleware, Plugins, and Modifiers are the main ways to extend Iron with new functionality. Most extensions that would be provided by middleware in other web frameworks are instead addressed by the much simpler Modifier and Plugin systems.

Modifiers allow external code to manipulate Requests and Response in an ergonomic fashion, allowing third-party extensions to get the same treatment as modifiers defined in Iron itself. Plugins allow for lazily-evaluated, automatically cached extensions to Requests and Responses, perfect for parsing, accessing, and otherwise lazily manipulating an http connection.

Middleware are only used when it is necessary to modify the control flow of a Request flow, hijack the entire handling of a Request, check an incoming Request, or to do final post-processing. This covers areas such as routing, mounting, static asset serving, final template rendering, authentication, and logging.

Iron comes with only basic modifiers for setting the status, body, and various headers, and the infrastructure for creating modifiers, plugins, and middleware. No plugins or middleware are bundled with Iron.

Performance

Iron averages 72,000+ requests per second for hello world and is mostly IO-bound, spending over 70% of its time in the kernel send-ing or recv-ing data.*

* Numbers from profiling on my OS X machine, your mileage may vary.

Core Extensions

Iron aims to fill a void in the Rust web stack - a high level framework that is extensible and makes organizing complex server code easy.

Extensions are painless to build. Some important ones are:

Middleware:

Plugins:

Both:

This allows for extremely flexible and powerful setups and allows nearly all of Iron's features to be swappable - you can even change the middleware resolution algorithm by swapping in your own Chain.

* Due to the rapidly evolving state of the Rust ecosystem, not everything builds all the time. Please be patient and file issues for breaking builds, we're doing our best.

Underlying HTTP Implementation

Iron is based on and uses hyper as its HTTP implementation, and lifts several types from it, including its header representation, status, and other core HTTP types. It is usually unnecessary to use hyper directly when using Iron, since Iron provides a facade over hyper's core facilities, but it is sometimes necessary to depend on it as well.

Installation

If you're using Cargo, just add Iron to your Cargo.toml:

[dependencies.iron]
version = "*"

The documentation is hosted online and auto-updated with each successful release. You can also use cargo doc to build a local copy.

Check out the examples directory!

You can run an individual example using cargo run --bin example-name inside the examples directory. Note that for benchmarking you should make sure to use the --release flag, which will cause cargo to compile the entire toolchain with optimizations. Without --release you will get truly sad numbers.

Getting Help

Feel free to ask questions as github issues in this or other related repos.

The best place to get immediate help is on IRC, on any of these channels on the mozilla network:

  • #rust-webdev
  • #iron
  • #rust

One of the maintainers or contributors is usually around and can probably help. We encourage you to stop by and say hi and tell us what you're using Iron for, even if you don't have any questions. It's invaluable to hear feedback from users and always nice to hear if someone is using the framework we've worked on.

Maintainers

Jonathan Reem (reem) is the core maintainer and author of Iron.

Commit Distribution (as of 8e55759):

Jonathan Reem (415)
Zach Pomerantz (123)
Michael Sproul (9)
Patrick Tran (5)
Corey Richardson (4)
Bryce Fisher-Fleig (3)
Barosl Lee (2)
Christoph Burgdorf (2)
da4c30ff (2)
arathunku (1)
Cengiz Can (1)
Darayus (1)
Eduardo Bautista (1)
Mehdi Avdi (1)
Michael Sierks (1)
Nerijus Arlauskas (1)
SuprDewd (1)

License

MIT

logger's People

Contributors

adamreeve avatar aerialx avatar alexander-irbis avatar brycefisher avatar duelinmarkers avatar emberian avatar fiedzia avatar gsquire avatar iori-yja avatar lyddonb avatar matklad avatar maxrp avatar mcreinhard avatar mfeckie avatar nemo157 avatar nevdelap avatar phlmn avatar reem avatar robinst avatar roxasshadow avatar serprex avatar skylerlipthay avatar theptrk avatar tim-semba avatar tomprince avatar txgruppi avatar untitaker avatar viraptor avatar zmbush avatar zzmp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

logger's Issues

Relicense under dual MIT/Apache-2.0

This issue was automatically generated. Feel free to close without ceremony if
you do not agree with re-licensing or if it is not possible for other reasons.
Respond to @cmr with any questions or concerns, or pop over to
#rust-offtopic on IRC to discuss.

You're receiving this because someone (perhaps the project maintainer)
published a crates.io package with the license as "MIT" xor "Apache-2.0" and
the repository field pointing here.

TL;DR the Rust ecosystem is largely Apache-2.0. Being available under that
license is good for interoperation. The MIT license as an add-on can be nice
for GPLv2 projects to use your code.

Why?

The MIT license requires reproducing countless copies of the same copyright
header with different names in the copyright field, for every MIT library in
use. The Apache license does not have this drawback. However, this is not the
primary motivation for me creating these issues. The Apache license also has
protections from patent trolls and an explicit contribution licensing clause.
However, the Apache license is incompatible with GPLv2. This is why Rust is
dual-licensed as MIT/Apache (the "primary" license being Apache, MIT only for
GPLv2 compat), and doing so would be wise for this project. This also makes
this crate suitable for inclusion and unrestricted sharing in the Rust
standard distribution and other projects using dual MIT/Apache, such as my
personal ulterior motive, the Robigalia project.

Some ask, "Does this really apply to binary redistributions? Does MIT really
require reproducing the whole thing?" I'm not a lawyer, and I can't give legal
advice, but some Google Android apps include open source attributions using
this interpretation. Others also agree with
it
.
But, again, the copyright notice redistribution is not the primary motivation
for the dual-licensing. It's stronger protections to licensees and better
interoperation with the wider Rust ecosystem.

How?

To do this, get explicit approval from each contributor of copyrightable work
(as not all contributions qualify for copyright, due to not being a "creative
work", e.g. a typo fix) and then add the following to your README:

## License

Licensed under either of

 * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)

at your option.

### Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any
additional terms or conditions.

and in your license headers, if you have them, use the following boilerplate
(based on that used in Rust):

// Copyright 2016 logger Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

It's commonly asked whether license headers are required. I'm not comfortable
making an official recommendation either way, but the Apache license
recommends it in their appendix on how to use the license.

Be sure to add the relevant LICENSE-{MIT,APACHE} files. You can copy these
from the Rust repo for a plain-text
version.

And don't forget to update the license metadata in your Cargo.toml to:

license = "MIT OR Apache-2.0"

I'll be going through projects which agree to be relicensed and have approval
by the necessary contributors and doing this changes, so feel free to leave
the heavy lifting to me!

Contributor checkoff

To agree to relicensing, comment with :

I license past and future contributions under the dual MIT/Apache-2.0 license, allowing licensees to chose either at their option.

Or, if you're a contributor, you can check the box in this repo next to your
name. My scripts will pick this exact phrase up and check your checkbox, but
I'll come through and manually review this issue later as well.

Logger does not reflect actual listening address and port

When asking Iron to listen on localhost:0, the kernel assigns an unused port number, and getaddrinfo resolves localhost to 127.0.0.1. The actual address can be displayed via format!("{}", listening.socket) where listening is an instance of the type returned by Iron::http and friends.

Example output from racerd

The first line is my own logging, and the second line is from this crate.

racerd listening at 127.0.0.1:54663
GET http://localhost:0/ping -> 200 OK (0.086167 ms)

Discussion

I'm not familiar with all members of the Request type, but it seems that Iron would need to pass in either the address or a reference to the listening server in order to access this information.

Usage info

With the switch to log crate, we need to update README (and maybe some other places) to inform users on how to set it up.

logger-0.3 no longer builds

/Users/vesakaihlavirta/.multirust/toolchains/stable/cargo/registry/src/github.com-0a35038f75765ae4/logger-0.0.3/src/lib.rs:80:57: 80:75 note: in this expansion of try! (defined in <std macros>)
<std macros>:6:1: 6:32 help: run `rustc --explain E0277` to see a detailed explanation
<std macros>:6:1: 6:32 note: required by `core::convert::From::from`
<std macros>:6:1: 6:32 error: the trait `core::convert::From<term::Error>` is not implemented for the type `std::io::error::Error` [E0277]
<std macros>:6 $ crate:: convert:: From:: from ( err ) ) } } )

I suppose #72 could be related

Latest Term breaks Build

The latest term breaks the build, probably would be good to set some semantic versions to depend on

Unable to build against 0.13.0 (nightly)

Dying on
unresolved import iron::errors::FileError.
and
unresolved import std::vec::MoveItems.

Wasn't able to figure out a fix (my first day with Rust!), but I did notice from the docs that std::vec no longer includes MoveItems in nightly (http://doc.rust-lang.org/std/vec/), which is consistent with the second error message.

Refactor for best Rust practices and Iron conventions

This is a blanket issue to refactor this middleware to be more efficient, more rusty, and use better conventions.

In particular this middleware unnecessarily uses String and Vec in many places, which leads to unnecessary clones of data and is likely to be pretty slow.

Only print on RUST_LOG=4

This seems like a debugging tool. Should it be used when Rust is not in a debugging mode?

What about using debug! instead of println! to only print when we are trying to debug?

Then again, this might not be helpful, as a user wants this data, but it would be nice if they could turn it on and off through an environment variable instead of having to recompile their code.

This crate does not build

Maybe related to #80 .

src/consumer/http.rs:20:11: 20:22 error: the trait bound `for<'r, 'r, 'r> logger::Logger: std::ops::Fn<(&'r mut iron::Request<'r, 'r>,)>` is not satisfied [E0277]
src/consumer/http.rs:20     chain.link_before(logger_before);
                                  ^~~~~~~~~~~
src/consumer/http.rs:20:11: 20:22 help: run `rustc --explain E0277` to see a detailed explanation
src/consumer/http.rs:20:11: 20:22 note: required because of the requirements on the impl of `iron::BeforeMiddleware` for `logger::Logger`
src/consumer/http.rs:20:11: 20:22 error: the trait bound `for<'r, 'r, 'r> logger::Logger: std::ops::FnOnce<(&'r mut iron::Request<'r, 'r>,)>` is not satisfied [E0277]
src/consumer/http.rs:20     chain.link_before(logger_before);
                                  ^~~~~~~~~~~
src/consumer/http.rs:20:11: 20:22 help: run `rustc --explain E0277` to see a detailed explanation
src/consumer/http.rs:20:11: 20:22 note: required because of the requirements on the impl of `iron::BeforeMiddleware` for `logger::Logger`
src/consumer/http.rs:21:11: 21:21 error: the trait bound `for<'r, 'r, 'r> logger::Logger: std::ops::Fn<(&'r mut iron::Request<'r, 'r>, iron::Response)>` is not satisfied [E0277]
src/consumer/http.rs:21     chain.link_after(logger_after);
                                  ^~~~~~~~~~
src/consumer/http.rs:21:11: 21:21 help: run `rustc --explain E0277` to see a detailed explanation
src/consumer/http.rs:21:11: 21:21 note: required because of the requirements on the impl of `iron::AfterMiddleware` for `logger::Logger`
src/consumer/http.rs:21:11: 21:21 error: the trait bound `for<'r, 'r, 'r> logger::Logger: std::ops::FnOnce<(&'r mut iron::Request<'r, 'r>, iron::Response)>` is not satisfied [E0277]
src/consumer/http.rs:21     chain.link_after(logger_after);
                                  ^~~~~~~~~~
src/consumer/http.rs:21:11: 21:21 help: run `rustc --explain E0277` to see a detailed explanation
src/consumer/http.rs:21:11: 21:21 note: required because of the requirements on the impl of `iron::AfterMiddleware` for `logger::Logger`

Built with Rust Nightly 1.12, Iron 0.3.

Logger doesn't log errors

I don't know whether this is a bug in iron/logger or iron/router, but when the router has a 404 or 301 response, it returns an Err, and logger doesn't log anything. Either router should return an Ok with the 401 or 301 status, or logger should handle logging when there's an error. I'm thinking it's the latter.

Example app demonstrating this problem:

extern crate iron;
extern crate logger;
extern crate router;

use iron::prelude::*;
use iron::status;

use logger::Logger;
use router::Router;

fn handle_hello(_ : &mut Request) -> IronResult<Response> {
    Ok(Response::with((status::Ok, "Hello world")))
}

fn main() {
    let (logger_before, logger_after) = Logger::new(None);

    let mut router = Router::new();

    router.get("/hello", handle_hello);

    let mut chain = Chain::new(router);

    chain.link_before(logger_before);
    chain.link_after(logger_after);

    Iron::new(chain).http("0.0.0.0:8080").unwrap();
}

error: type `collections::string::String` does not implement any method in scope named `push_char`

src/format.rs:74:47: 74:59 error: type `collections::string::String` does not implement any method in scope named `push_char`
src/format.rs:74                             Some(c) => { name.push_char(c); }
                                                               ^~~~~~~~~~~~
src/format.rs:115:55: 115:67 error: type `collections::string::String` does not implement any method in scope named `push_char`
src/format.rs:115                                     Some(c) => { name.push_char(c); }
                                                                        ^~~~~~~~~~~~
src/format.rs:122:37: 122:49 error: type `collections::string::String` does not implement any method in scope named `push_char`
src/format.rs:122                 Some(c) => { string.push_char(c); }
                                                      ^~~~~~~~~~~~
error: aborting due to 3 previous errors
Build failed, waiting for other jobs to finish...
Could not compile `logger`.

building recommended way breaks

adding:

[dependencies.logger]

git = "https://github.com/iron/logger.git"

to my cargo.toml, and running this code:

extern crate iron;
extern crate router;
extern crate logger;

use iron::prelude::*;
use iron::status;
use router::Router;
use logger::Logger;

fn main() {
    let (logger_before, logger_after) = Logger::new(None);

    let mut router = Router::new();
    router.get("/", handler);
    router.get("/generate", generate_handler);

    let mut chain = Chain::new(router);
    chain.link_before(logger_before);
    chain.link_after(logger_after);

    Iron::new(chain).http("localhost:3000").unwrap();
}

fn handler(_: &mut Request) -> IronResult<Response> {
    Ok(Response::with((status::Ok, "OK")))
}

fn generate_handler(_: &mut Request) -> IronResult<Response> {
    Ok(Response::with((status::Ok)))
}

produces the following error:

src/main.rs:22:11: 22:22 error: the trait `for<'r, 'r, 'r> core::ops::Fn<(&'r mut iron::request::Request<'r, 'r>,)>` is not implemented for the type `logger::Logger` [E0277]
src/main.rs:22     chain.link_before(logger_before);
                         ^~~~~~~~~~~
src/main.rs:22:11: 22:22 help: run `rustc --explain E0277` to see a detailed explanation
src/main.rs:23:11: 23:21 error: the trait `for<'r, 'r, 'r> core::ops::Fn<(&'r mut iron::request::Request<'r, 'r>, iron::response::Response)>` is not implemented for the type `logger::Logger` [E0277]
src/main.rs:23     chain.link_after(logger_after);

changing it to:

[dependencies]
iron = "*"
router = "*"
logger = "*"

removes the error. what is the difference? why does the way of building listed in the readme break?

Logger fails when it can't open a terminal

Thank you for such a handy middleware stack!

When I use the logger in a Heroku app, it prints:

2014-09-18T16:20:53.267041+00:00 heroku[router]: at=info method=GET path="/" host=radiant-cliffs-2720.herokuapp.com request_id=fe3b8e00-e4fc-446a-8441-8deba5340382 fwd="<DELETED>" dyno=web.1 connect=1ms service=6ms status=200 bytes=77
2014-09-18T16:20:53.265665+00:00 app[web.1]: Logger could not open terminal
2014-09-18T16:20:53.642865+00:00 app[web.1]: Logger could not open terminal

As far as I know, the standard output of a Heroku application is piped off to a logging daemon somewhere, and it isn't attached to a real terminal. To reproduce, see this blog post, which explains how to deploy iron apps to Heroku.

Release 0.0.2

It would be great to get the a new version of logger up on crates.io now that it's building again.

Windows: All requests fail with default format: NotSupported

When using the logging middleware, all requests fail with the following log messages:

2016-03-28T21:44:08+07:00 ERROR iron::iron - Error handling:
Request {
    url: Url { scheme: "http", host: Domain("localhost"), port: 3000, path: ["12345"], username: None, password: None, query: None, fragment: None }
    method: Get
    remote_addr: V6([::1]:59540)
    local_addr: V6([::1]:3000)
}
Error was: Error { repr: Custom(Custom { kind: Other, error: NotSupported }) }

The NotSupported seems to come from term indicating that the used terminal doesn't support the requested term capabilities.

The relevant source code used:

let mut chain = Chain::new(router);

let (logger_before, logger_after) = Logger::new(None);
chain.link_before(logger_before);
chain.link_after(logger_after);

Chaning the format string to not use colors solves the problem.

Rust: rustc 1.9.0-nightly (d5a91e695 2016-03-26)
Iron: 0.3.0
Logger: 0.0.3
OS: Windows 7 SP 1
Shell: zsh
Env: msys2
I also used ConEmu, if that's relevant.

deprecated stuff

logger/src/lib.rs:70:37
   |
70 |         .target(env_logger::Target::Pipe(Box::new(file)))
   |                                     ^^^^
   |
   = note: `#[warn(deprecated)]` on by default

warning: `solana-logger` (lib) generated 1 warning

Tries to use a terminal when running under Docker, and causes requests to fail

If I take a basic Iron app with logger 0.0.3:

fn main() {
    // Set up very basic logging to the console.
    env_logger::init();

    // Declare our REST API using Rustless, which is much tidier than using
    // bare Iron APIs.
    let api = rustless::Api::build(|api| {
        // ... SNIPPED  ...
    });
    let app = rustless::Application::new(api);

    // Put our app into a middleware chain so we can attach the logger,
    // etc.
    let mut chain = Chain::new(app);

    // Call the logger middleware at the beginning and end of our request
    // chain.
    let (logger_before, logger_after) = Logger::new(None);
    chain.link_before(logger_before);
    chain.link_after(logger_after);

    // Run our web server.
    println!("Listening on 0.0.0.0:3000");
    match Iron::new(chain).http("0.0.0.0:3000") {
        Ok(_) => {},
        Err(ref e) => println!("Could not start server: {}", e),
    }
}

…and run it under Docker as:

docker run --rm myimage

I get:

ERROR:iron::iron: Error handling:
Request {
    url: Url { scheme: "http", host: Ipv4(172.17.0.11), port: 3000, path: ["health"], username: None, password: None, query: None, fragment: None }
    method: Get
    remote_addr: V4(172.17.42.1:35256)
    local_addr: V4(0.0.0.0:3000)
}
Error was: CouldNotOpenTerminal

Running docker run --rm myimage env does not show the TERM variable as being set. But it looks like it's trying to open a terminal anyway, instead of just logging to stdout.

There's probably a way to reproduce this without docker; I'm investigating further.

Docs 404

Documentation link provided in readme is broken

500 Server Error ! logger = "0.1.0"

[dependencies]
iron = "0.4.0"
router = "0.2.0"
logger = "0.1.0"
extern crate iron;
extern crate router;
extern crate logger;

use iron::prelude::*;
use iron::status;
use router::Router;
use logger::Logger;

fn handler(req: &mut Request) -> IronResult<Response> {
    Ok(Response::with((status::Ok, "Hello world!")))
}

fn main() {

    let mut router = Router::new();
    router.get("/", handler);
    router.get("/:query", handler);

    let mut chain = Chain::new(router);

    let (logger_before, logger_after) = Logger::new(None);
    chain.link_before(logger_before);
    chain.link_after(logger_after);

    Iron::new(chain).http("localhost:3000").unwrap();

}

I got a 500 server error if I link logger to chain.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.