In part 1 of this series, we looked at how you could use Azure Functions to host a static website. The function basically served up static files it read off the file system and delivered them as HTTP responses. Websites though are not complete without logging! Logging is already supported in functions when one calls the context.log method, however if you want custom logging that is more easily parseable, you can implement a table output binding and easily write custom logs out to the binding.
If you have not already done so, setup a website according to the instructions in the first post, then you’ll be ready to add a custom log to the post.
var fs = require("fs")
var mime = require('mime-types')
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
module.exports = function (context, req) {
var file="index.html"
if (req.query.file) {
file=req.query.file
}
file = file.replace(///g, "");
fs.readFile(__dirname + "content" + file, function(err, data) {
context.log('GET ' + __dirname + "content" + file);
context.bindings.outputTable = {
"partitionKey": "log",
"rowKey":uuidv4(),
"method": req.method,
"file": file,
"from": req.headers["x-forwarded-for"],
"useragent": req.headers["user-agent"],
"referer": req.headers["referer"]
}
if (!err){
var contentType = mime.lookup(file)
context.bindings.outputTable.status = 200
context.res = {
status: 200,
body: data,
isRaw: true,
headers: {
'Content-Type': contentType
}
};
}else{
context.log("Error: " + err)
context.bindings.outputTable.status = 404
context.res = {
status: 404,
body: "Not Found.",
headers: {
}
};
}
context.done()
});
};
Conclusion
As you’re beginning to see, you can do all sorts of things with function apps. A static website with custom logging is one of many different ways to use it. Next time, we’ll look at how to add a feedback form to the a site using an Azure function with a CAPTCHA.
Stay tuned for part 3
Microsoft Azure and Amazon Web Services (AWS) are two of the most popular cloud platforms.…
Cloud management is difficult to do manually, especially if you work with multiple cloud…
Azure’s scalable infrastructure is often cited as one of the primary reasons why it's the…
https://www.youtube.com/watch?v=wDzCN0d8SeA Watch our "Unlocking the Power of AI in your Software Development Life Cycle (SDLC)"…
FinOps is a strategic approach to managing cloud costs. It combines financial management best practices…
Using Kubernetes with Azure combines the power of Kubernetes container orchestration and the cloud capabilities…