erlangcowboynitrogen

Best way to log access to web pages


One of my website is using Nitrogen with a Cowboy server. I would like to log every access to web pages just like Apache does with access.log. What would be the best way to do that ?


Solution

  • You can use cowboy middlewares https://ninenines.eu/docs/en/cowboy/1.0/guide/middlewares/

    Just create a simple log module:

    -module(app_web_log).
    -behaviour(cowboy_middleware).
    
    -export([execute/2]).
    
    execute(Req, Env) ->
        {{Peer, _}, Req2} = cowboy_req:peer(Req),
        {Method, Req3} = cowboy_req:method(Req2),
        {Path, Req4} = cowboy_req:path(Req3),
        error_logger:info_msg("~p: [~p]: ~p ~p", [calendar:universal_time(), Peer, Method, Path]),
        {ok, Req4, Env}.
    

    and add it in list of middlwares:

        {ok, _} = cowboy:start_http(http, 100, [{port, 8080}], [
                {env, [{dispatch, Dispatch}]},
                {middlewares, [cowboy_router, app_web_log, cowboy_handler]}]).