title: How to log the selected director>backend in varnishncsa
body: <p>I have multiple backend servers and I "round-robin" between them using a director.  </p>
  
  <p>Is there a way and - if there is - how to log which backend gets used (either the backend name or the backend host name)?<br>
  The above refers to using <code>std.log("key:value")</code> and <code>%{VCL_Log:*key*}x</code> with varnishncsa.</p>
  
  <p>My vcl config:</p>
  
  <pre><code>backend aws_frontend1 {
    .host = "aws1.domain.mobi";
    .port = "80";
  }
  backend aws_frontend2 {
    .host = "aws2.domain.mobi";
    .port = "80";
  }
  
  director lb_aws_frontend round-robin {
    {
      .backend = aws_frontend1;
    }
    {
      .backend = aws_frontend2;
    }
  }
  
  sub vcl_recv {
    set req.backend = lb_aws_frontend;
    unset req.http.Cookie;
  }
  sub vcl_fetch {
    if (beresp.http.cache-control ~ "(no-cache|private)" || beresp.http.pragma ~ "no-cache") {
      set beresp.ttl = 0s;
    } else {
      set beresp.ttl = 168h;
    }
  }
  sub vcl_error {
    if (obj.status == 750) {
      set obj.status = 403;
      return(deliver);
    }
  }
  </code></pre>
  
  <h2>Edit:</h2>
  
  <p>Below is the updated code thanks to NITEMAN...
  This code prints out the backend name when a miss and "varnish cache" is a hit:</p>
  
  <pre><code>import std;
  
  backend aws_frontend1 {
    .host = "aws1.domain.mobi";
    .port = "80";
  }
  backend aws_frontend2 {
    .host = "aws2.domain.mobi";
    .port = "80";
  }
  
  director lb_aws_frontend round-robin {
    {
      .backend = aws_frontend1;
    }
    {
      .backend = aws_frontend2;
    }
  }
  
  sub vcl_recv {
    set req.backend = lb_aws_frontend;
    unset req.http.Cookie;
  }
  sub vcl_fetch {
    if (beresp.http.cache-control ~ "(no-cache|private)" || beresp.http.pragma ~ "no-cache") {
      set beresp.ttl = 0s;
    } else {
      set beresp.ttl = 168h;
    }
    std.log("backend_used:" + beresp.backend.name);
  }
  sub vcl_hit {
    std.log("backend_used:varnish cache");
  }
  sub vcl_error {
    if (obj.status == 750) {
      set obj.status = 403;
      return(deliver);
    }
  }
  </code></pre>