Log Server Based on Node. js and express, node. jsexpress

Source: Internet
Author: User

Log Server Based on Node. js and express, node. jsexpress

First of all, the significance of this article is greater than the actual value. If I joined umeng directly in the game as I intended, the information would be more comprehensive and simple. However, there are always many people who use their outdated or wrong experiences to say how bad they are and how good they are. Fortunately, I think I have a strong learning ability and a strong ability to solve problems. I am really interested in making a server + front-end.


1. Introduction to Node. js

Originally, javascript was purely a front-end language and basically made webpages richer and more dazzling. However, after the emergence of Node. js, javacript became a language that is common to both the frontend and backend. For example, Netease's pomelo is a game server Engine Based on Node. js. Many large companies around the world have begun to use Node. js to build their server backend.

Node. js has the following features:

1. Based on the javacriplanguage, the mass base is very solid. 70% of the libraries on github are written by javacrip. the libraries with over stars are almost clear javascript.

2. google-based V8 javascript interpretation engine is very fast. As a server language, it may not be the fastest, but it must not be slow.

3. asynchronous + callback operations make the Node. js server highly concurrent

4. The npm and the community are huge, and the third-party libraries of Node. js are unimaginable.


II. Introduction to express

Express is a popular Http Server framework in Node. js. Through express, you can quickly build an http server to receive and process requests such as 'get' POST.

You can use express-generator to generate a basic express server project.


Iii. log server code

App. js code:


var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var routes = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(morgan('dev'));

// uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public'), { noCache:1, maxAge: 0 }));

app.use('/', routes);

//app.disable('etag');

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

app.listen(8080)

module.exports = app;

Index. js code:



var express = require('express');
var router = express.Router();
var fs = require('fs')

/* GET home page. */
router.get('/', function(req, res) {
  fs.readFile('logs/all-logs.log', function(err, data) {
    if (err) {
      var list = ['file not find']
      res.render('index', { title: 'Log Server', logs: list});
    } else {
      var list = data.toString().split('\n');
      res.render('index', { title: 'Log Server', logs: list});
    }
  });
});

var winston = require('winston');
var logger = new winston.Logger({
  transports: [
    new winston.transports.File({
      level: 'info',
      filename: './logs/all-logs.log',
      handleExceptions: true,
      json: true,
      maxsize: 5242880, //5MB
      maxFiles: 5,
      colorize: false
    }),
    new winston.transports.Console({
      level: 'debug',
      handleExceptions: true,
      json: false,
      colorize: true
    })
  ],
  exitOnError: false
});

router.post('/', function(req, res) {
  logger.log('info', req.body)
  // req.body.log   req.body.platform  req.body.stack
  res.send('1');
});

module.exports = router;

The client sends error logs:



local csdebug = {}

function csdebug.send(fmt, ...)
    local log = string.format(tostring(fmt), ...);
    local platformCode = cc.Application:getInstance():getTargetPlatform();
    local platform = 'unknown';
    if platformCode == 0 then
    	platform = 'windows'
    elseif platformCode == 3 then
    	platform = 'android'
    elseif platformCode == 4 then
    	platform = 'ios';
    elseif platformCode == 5 then
    	platform = 'ipad'
    end

    local xhr = cc.XMLHttpRequest:new()
    xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING
    xhr:open("POST", "http://"..GameConfig.LogServerIp)
    xhr:setRequestHeader('Content-Type', 'application/json')
    local function onReadyStateChange()
        if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
            print(xhr.response)
        else
            print("xhr.readyState is:", xhr.readyState, "xhr.status is: ",xhr.status)
        end
    end

    xhr:registerScriptHandler(onReadyStateChange)
    local cjson = require('cjson');

	local json = cjson.encode({log=log, platform=platform, stack=debug.traceback("", 3)});
	print(json)
	--local json = string.format('{"log":"%s","platform":"%s"}', log, platform, debug.traceback("", 3));
    xhr:send(json)
end

return csdebug
The most important thing is the use of HttpRequest in the cocos2d-x. If the body content is directly sent through send, url-encoding is not required for the string. In addition, the node. js server receives json data and can directly use its content.


When the above function is called in the function that prints the error log and the function of main. lua's _ g1_trackback _, the error log can be sent to the server.

Iv. Explanations:

1. The most basic function of express is Web routing. To put it bluntly, it is what the server should do when requesting the corresponding address from the server. For example, index. js is the core function of log. Index. js is in the routes folder. We mount index. js to the '/' root directory, that is, when we directly access "http: // localhost: 8888", we will call the index. js related functions. In index. in js. get and router. post is attached with two processing functions for processing: a. When a browser accesses a webpage, it reads the log file and outputs it. This function is used to view the log Content. B. When the client sends the log content to the server through post, the log module records the content in the text.

2. In express, backend data and front-end web page rendering are combined through the template engine. The template is placed in views. Well-known template engines include jade, ejs, and Harvard. The so-called template engine is an interpreter that defines a format. We write webpage Templates using corresponding rules, and the template engine automatically compiles them into html and finally delivers them to the client (browser). Here I am using ejs, and its syntax is similar to html.

3. To run the server, enter node app in the command line. If webstorm is used, you can directly debug app. js. webstorm supports node. js very well. Debugging is perfect.

4. During normal development, you can use the nodemon app to run the server. Nodemon is a third-party library and needs to be installed. Its function is to detect js file changes and automatically restart the server if any changes occur. With it, you can write as you get the development server without restarting the server constantly.

5. About browser cache. This article is very clear. The most foolish way is to use F5 to refresh the web page. If I used to press enter in the address bar at the beginning to open the web page, it is likely to be affected by the browser cache, the old content is displayed (no matter whether the server is updated at this time ). When you use F5 to refresh a webpage, the browser cache is forcibly refreshed.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.